9 ms·
When is it preferable to composition?
by no_wave 9y ago
When is it preferable to composition?
- scriptkiddy 9y agoWhen modeling objects that need to encapsulate mutable data and pass messages between one another.
- pka 9y agoInheritance is orthogonal to that. I.e. Erlang, an (impure) functional language without inheritance was literally built for that sort of thing.
- scriptkiddy 9y agoOh, 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.