Composition is a bit more like building a solution as you go from the bottom up - you solve the sub problems one at a time and then just combine these solutions together iteratively to solve the larger problem. When things change, it's quite easy to change these small solutions, throw some away, build new ones, and recombine them. It's a much more abstract, much more flexible way to piece together your overall solution.
If another body of code entirely was written and tested using As, without knowing that Bs exist, it may not work if given a B, unless that B happened to perform exactly the same as an A in whatever (unknown, unknowable) ways matter to that other body of code.
An object's interface is its specification. But most objects are woefully underspecified, with types (if you're lucky) and perhaps a bit of prose explaining what it's supposed to do. Preconditions and postconditions are rare, laws and properties are rarer still. Languages that are able to test those things hold are even rarer.
My own recommendation is to inherit only from abstract parents, and if your language supports it, to make any concrete class final. If you need some behaviour to be overridable at time of use, apply the Strategy pattern. There's a cost to this: you need to implement Strategy, and you will not think of all cases where behaviour should be overridable. But the cost of random errors that crop up at run time is IMO likely to be higher.
The problem is that languages such as Java mix up the specification and the actual implementation, as a result you end up with an inheritance model that is rigid and doesn't account for the messiness of the real word, in other words things in the real world are not often related in a neat parent/child way.
Granted, Java does provide interfaces which can be viewed as a way to specify composition even though that doesn't appear to be it's intended use.
In other words, objects are composed of their dependent objects. I think this is where the idea of dependency injection comes from (though I find dependency injection frameworks complicated often, that's another story).
Building abstractions around useful/loosely coupled ways of encapsulating dependencies, as mentioned elsewhere in this thread "bottom up", is part of an organic process that evolves into getting design right. A huge "lever" that you can lean on in this process is being able to mock the things that you want, while also being able to use the "real" versions of the things that you want. This allows your code to pretty much always be testable and flexible.
It takes some practice, but once you get it your code grows so much better.
It's true. I had a bit of a roundabout journey to getting this idea.
Studying CS, I learned a ton about implementation inheritance, and only a bit about composition - enough to sort of answer a question about it, but not really get the feeling. So overall I didn't use it much.
When I started working, I saw implementation inheritance used a ton and got the impression that it really made things way too complex. There was more to the complexity than just this of course (design patterns everywhere, convoluted abstractions, strange monolith tools, etc) but it didn't help.
Later I started learning about FP, where composition is just second nature, and frankly one of the main methods of abstraction you get. So learning how to compose things came from functions.
Over the past few months I've come back to more OOP, and I've been using composition a whole lot more. And it does make a huge difference, and I don't think I've used any sort of inheritance for my own code at all at this point.
So yeah, I agree and it is a journey.
- Inheritance is static. Composition can be dynamic.
- Composition avoids "fragile base class" problem.
- Modifying base class requires access to source code. Composition does not.This isn't to say there aren't valid use cases for inheritance (eg. runtime polymorphism), though if something can be accomplished through composition, it's usually the better approach as it only modifies inner details of an object, and not the external interface (of which the inherited classes are part).
I don't have much time now, but a fundamental difference is that inheritance happens at compile time (it's rare/nonexistent that you can change the class hierarchy at runtime) while composition happens at runtime – this means that with composition one can change the behavior of a class at runtime by inserting in a field a different implementation of an interface, for example.
Thanks!
public Map<String, someDataHolder> inheritedFormatData () {
Map<String, someDataHolder> formattedData = new ArrayList<>();
for (Record record : records) {
formattedData.put('tabA', processTabA(record));
formattedData.put('tabB', processTabB(record));
formattedData.put('tabC', processTabC(record));
formattedData.put('tabD', processTabD(record));
}
}
And that works well enough, until there was a need for having variations. In that case they just subclassed this formatter class and provided an override for "proccessTabB" for example.The problem is that this week, I've been tasked with adding a new tab, tabE. There's no "processTabE" method to override. I basically have a few unpalatable choices:
- Directly add something like "formattedData.put('tabE', processTabE(record));", and the method "processTabE", to the base class. The danger here is that I have to make sure I don't accidentally break some behavior in one of the dozens of child classes (there's more complex inheritance than I'm sharing in this simple example).
- Inherit, then add another method that loops through "records" again and only processes tabE. That's safer from the point of view of inheritance, but it's very wasteful to loop through all the records more than once (there could be as many as a million in my particular case).
- Copy-paste the base class code into a new class. That solves the above problems but, ugh.
Consider a different approach:
public Map<String, someDataHolder> composedFormatData (List<Tabs> tabs) {
Map<String, someDataHolder> formattedData = new ArrayList<>();
records.forEach(record -> tabs.forEach(tab -> tab.process());
tabs.forEach(tab -> {
String mapKey = tab.getKey();
formattedData.put(mapKey, tab.getProcessedData());
})
}
If we define a "Tab" type, with method for storing a key, processing and storing records, and providing that processed data, we can create a list of as many of these tabs as we want, and define each tab's manner for processing the data. Adding a variation to the report generation class is now a matter of defining a different list of tabs and passing that in. No more inheritance woes, plus it nudges you in the direction of better encapsulation of your state (ie each tab is responsible for itself, rather than that logic living in some base super class). Hope this concrete example helps.
Can someone summarize why this is better than say inheritance?
I can possibly understand the value of composition where you need a large team to be able to constantly add and remove functionality to a code base with this without having to mess with APIs override methods, etc...
But is there a fundamental benefit of composition over inheritance in ever circumstance? (I've read a number of articles on this recently and I am not understanding the benefits vs the complications it adds)