4 ms·
I've been thinking about this a lot lately, and my current view of the world is that inheritance as a way of implementing code reuse leads to poor mental models
by lamontcg 5y ago
I've been thinking about this a lot lately, and my current view of the world is that inheritance as a way of implementing code reuse leads to poor mental models and practices.
A better approach is probably to implement the code reuse model as an implementation of a public interface, which the subclass then implements and delegates. The cause of the brittle base class problem is likely that the interface between the base class and the subclasses is often not defined very well so it tends to not get engineered very well, and then external code can depend upon the implementation of the base class creating the brittleness.
So instead of having Banana and Orange that inhert from Fruit and having a container like a List<Fruit> if you use composition instead you get Banana and Orange that implement IFruit through delegating to Fruit and your containers are List<IFruit>'s now (you can't see the details of how Banana and Orange implement IFruit they just promise to implement it). You are now free to create FruitV2 which is a snazzy new implementation of IFruit, and you can inject it into Banana and Orange without breaking anyone who depends upon IFruit. It also becomes more apparent when you are making breaking changes because you wind up editing IFruit. You can also use DI or a DI Container (if you must) to control injection of behavior into objects.
And really inheritance is just delegation to another class dressed up and made simple to use. It is the exposure of that base class publicly and without good interface design that makes it bad.
Implicit in what I just wrong there though is that encapsulation is a very good thing and you should only depend on interfaces. I don't know why the author argues that encapsulation is bad. I've lived in the ruby land for 10 years with no encapsulation and in the long run it is literally fucking horrible since anything can have been accessed by some user somewhere with tools like `send()` and any change can potentially be breaking, and users will whine about SemVer even though you certainly never documented what they were doing and would have yelled loudly at them for attempting it if you'd ever known. Fences and neighbors and the tragedy of the commons and all that....