DEV Community

Jonathan Kuhl
Jonathan Kuhl

Posted on

1 1

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?

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
rhymes profile image
rhymes

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay