DEV Community

Jonathan Kuhl
Jonathan Kuhl

Posted on

When isn't inheritance used?

I was asked in an interview "when would you not use inheritance." And I paused because the only thing I could articulate was "when it doesn't make sense?"

This was for a .NET position, by the way.

The thing that puzzled me about this question was that I didn't really know how to say it. You don't use inheritance when it doesn't apply to the software architecture. And that's more or less what I said, but I was wholly unsatisfied with my answer.

After the interview was done as I was doing my after-action report, I had this sneaking suspicion that he wanted me to mention composition. And as I write this post, I also feel like I should have added immutability, you don't want inheritance on objects that are meant to be immutable (like Java's String class).

But now it bothers me. What would be a good answer to that question?

Top comments (2)

rhymes profile image

Composition is almost always the better choice. It favors reusability and you can inject dependencies which also makes testing easier. I guess it's also easier to move things around with it.

Another pro of composition is that inheritance (especially multiple inheritance) makes it hard to track down dependencies and sometimes introduces ordering problems (if you inherit from X and Y and both inherit from A then you're inheriting from A twice in theory).

Inheritance tightly couples implementation details between the sub and superclass, whereas composition favors using just the interface.

I'd say inheritance is okay if there's an is a relationship and if your inheritance tree is really shallow (I wouldn't go past 1 in your own code TBH :D).

Another shortcoming of inheritance is that with composition it's easier to change implementation at runtime.