Hacker News new | ask | show | jobs
by timr 4359 days ago
"I was told about inheritance, but had to learn from other coworkers and experience that composition is much favored over inheritance."

You weren't taught that, because it isn't true. Inheritance is appropriate sometimes, composition at other times.

In particular, when a two objects are modeled by an ISA relationship, you should use inheritance. When they're modeled by HASA, you should use composition.

A Dog is not an Animal that includes Barkable and PeeOnHydrantable, and a SpaceShuttle is not a descendant of Airplane.

3 comments

You're missing the most important cases - there are cases where it could go both ways in terms of ISA vs. HASA, in which case (the article says) you should use HASA.

Just saying "use the tool appropriate to the job" dismisses the entire problem where in the real world, it isn't clear what that is.

I'm not responding to the article, I'm responding to the parent, who is saying that encapsulation is "much favored" over inheritance. It is not. At least, not amongst more experienced programmers.

Even in marginal cases, you can reasonably decide that a data model should use inheritance. There's no presumptive bias against it.

> A Dog is not an Animal that includes Barkable and PeeOnHydrantable, and a SpaceShuttle is not a descendant of Airplane

I think there is probably a lot of room for debate on this.

(Edited to make it less pithy and therefore probably much less irksome)

I don't see how this isn't circular. The principle is about the choice of how to model things.