3

Imagine I have the following code:

class A:
    pass

class B(A):
    pass

class C(A):
    def __init__(self):
        self.b = B()

Is the above code correct in terms of correct inheritance? I mean is it a good practice to reference another subclass in a subclass?

  • 1
    What is "correct inheritance"? – Doval Jul 9 '14 at 12:54
  • @Doval I have no idea, I look for best practices to learn the correct way. I had just a feeling that this doesn't look right. – Mehdi Sadeghi Jul 9 '14 at 13:09
  • I think this is a really great question. Actually there are cases in which such references would be considered bad practice, and I think your intuition is absolutely correct, it doesn't look right. The problem is, of course, to figure out, why it is so. In other words, to formalize the conditions underlying that intuition. – proskor Jul 9 '14 at 14:00
  • @proskor Thanks for your comment. I want to decouple everything as much as I can, therefore when I reference another class from same level of hierarchy it seems to me that I am breaking my habit. – Mehdi Sadeghi Jul 9 '14 at 15:29
  • 1
    Another reason why this feels bad may be that it might break the dependency inversion principle: 'High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.' – proskor Jul 9 '14 at 16:10
3

Bags and suitcases are both types of containers. You can also put bags inside suitcases, and vice versa. Containment doesn't care about inheritance, and inheritance doesn't care about containment.

The two concepts are entirely orthogonal, and as such there is no 'best practice' here.

  • Thanks for the example, it made it easier for me to understand. Unfortunately I can't vote up yet. – Mehdi Sadeghi Jul 9 '14 at 13:30
1

It depends. In some languages (like Java), you don't really have a choice because every class (except Object) is a subclass.

If class C needs some functionality from class B to do its work, but you can't describe instances of class C as also being instances of class B (C can't work as a drop-in replacement for B), then your design is absolutely correct.

  • Good to know that everything is subclass in Java. It shows that this type of inheritance is already in place in Java design and perhaps other languages. And the same here, I can't vote up yet. – Mehdi Sadeghi Jul 9 '14 at 13:38
  • Moreover, both answers are promising and I can't mark both as correct answer. Thanks anyway. – Mehdi Sadeghi Jul 9 '14 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.