Hacker News new | ask | show | jobs
by no_wave 3366 days ago
When is it preferable to composition?
1 comments

When modeling objects that need to encapsulate mutable data and pass messages between one another.
Inheritance is orthogonal to that. I.e. Erlang, an (impure) functional language without inheritance was literally built for that sort of thing.
Oh, you were asking about inheritance, not objects. My bad. I'd say composition is almost always preferable.

That said, single level inheritance can be useful if you need to have multiple different objects that require very similar business logic but contain vastly different data.

A good example of this is Django's class based `View` class. I'm not talking about all the mixin views Django offers, just the simple generic `View` class. It handles routing to specific methods based on HTTP request METHOD. That eliminates the need to write the same ~100loc over and over. The alternative would be to use function based views. However, with function based views you end up basically recreating what the class does anyways after checking for each HTTP request method.