Everyone says composition over inheritance. When i...
# random
u
Everyone says composition over inheritance. When is inheritance what I want?
s
Can you rephrase it, please?
s
You want inheritance when the two things share an "is-a" relationship
👍🏻 2
they're both the same thing, but one might have a slightly specialized behavior
The Liskov Substitution Principle (the "L" in "SOLID") offers some guidance on this
💯 1
u
Okay so youd use inheritance to modify some behavior transparently from caller, versus composition to add /share behavior?
c
The balance of abstraction is what is complicated. So if you have a class like Dog should you make a base class called Animal? or Organism? of course, if you need abstraction at those levels. Composition makes no sense in that case, an Organism does not contain a Dog. But, you can only use inheritance once (though there are ways around that). Where I think it makes more sense to stress composition is when you are trying to get things to work together. Should you extend a View Class for instance? or contain the View and then modify some of its behavior via something like a Decorator?
r
Avoid subclassing for sake of creating behavior. inheritance: avoid is as much as possible i would say. use it only when it makes perfect sense - such interfaces/ABC to define behavior. then subclass them to implement it. it makes it easier for oher programmers to understand your intent. subclassing for sake of creating new behavior does not make sense. think liskovs substituions principle.. and if you follow it you will understnad that there are very few cases where subclassing is effective. compositions makes it easier for other programmers to create or change implementation. whilst inheritance is harder since it always creates a chain reaction.
👍 1
1
💯 1
u
if you have such encapsulated behavior+state, and now you want to compose them, should now the enclosing class implement the subcomponent interfaces and just proxy the calls to each subcomponent?
i.e. is there a way to avoid this? in this way of doing stuff, topmost enclosing class just proxies stuff?
while I agree deep hierarchies will fuck you in the long run, people do this because it "saves" code for simple hierarchies, see the proxying above
m
The enclosing class does not have to proxy all of its components’ interfaces, but only those that make sense for its exposed behavior (public API). Or it could not proxy any method at all, and just use its components to provide a desired behavior. An example of this can be the “Aggregate Root” from Domain-Driven Design. Here is a nice piece on the subject: https://www.yegor256.com/2016/09/13/inheritance-is-procedural.html