230 points · by ingve · 1y ago · 209 comments
That is: an instance of a subclass calls a method defined on a parent class, which in turn may call a method that's been overridden by the subclass (or even another sub-subclass in the hierarchy) and that one in turn may call another parent method, and so on. It can easily become a pinball of calls around the hierarchy.
Add to that the fact that "objects" have state, and each class in the hierarchy may add more state, and modify state declared on parents. Perfect combinatory explosion of state and control-flow complexity.
I've seen this scenario way too many times in projects, and worse thing is: many developers think it's fine... and are even proud of navigating such a mess. Heck, many popular "frameworks" encourage this.
Basically: every time you modify a class, you must review the inner implementation of all other classes in the hierarchy, and call paths to ensure your change is safe. That's a horrendous way to write software, against the most basic principles of modularity and low coupling.
Of course these days with LTO the whole performance space is somewhat blurred since de-virtualisation can happen across whole applications at link time, and so the presumed performance cost can disappear (even if it wasn't actually a performance issue in reality). It's tough to create hard and fast rules in this case.
It's a much pleasurable and easier way to work, for me at least.
Trying to follow the flow through gazillion of objects with state changing everywhere is a nightmare and I rather not return to that.
public record Thing()
{
private string _state = "Initial";
public Thing Change() => this with { _state = "Changed" };
}This is why hierarchies should have limited depth. I'd argue some amount of "co-recursion" is to be expected: after all the point of the child class is to reuse logic of the parent but to overwrite some logic.
But if the lineage goes too deep, it becomes hard to follow.
> every time you modify a class, you must review the inner implementation of all other classes in the hierarchy, and call paths to ensure your change is safe.
I'd say this is a fact of life for all pieces of code which are reused more than once. This is another reason why low coupling high cohesion is so important: if the parent method does one thing and does it well, when it needs to be changed, it probably needs to be changed for all child classes. If not, then the question arises why they're all using that same piece of code, and if this refactor shouldn't include breaking that apart into separate methods.
This problem also becomes less pressing if the test pyramid is followed properly, because that parent method should be tested in the integration tests too.
That's the point: You can reuse code without paying that price of inheritance. You DON'T have to expect co-recursion or shared state just for "code-reuse".
And, I think, is the key point: Behavior inheritance is NOT a good technique for code-reuse... Type-inheritance, however, IS good for abstraction, for defining boundaries, to enable polymorphism.
> I'd say this is a fact of life for all pieces of code which are reused more than once
But you want to minimize that complexity. If you call a pure function, you know it only depends on its arguments... done. If you can a method on a mutable object, you have to read its implementation line-by-line, you have to navigate a web of possibly polymorphic calls which may even modify shared state.
> This is another reason why low coupling high cohesion is so important
exactly. Now, I would phrase it the other way around though: "... low coupling high cohesion is so important..." that's the reason why using inheritance of implementation for code-reuse is often a bad idea.
I actually can't imagine for the life of me why I'm defending OOP implementation hierarchies here- I guess I got so used to them at work, I've changed my strategy from opposing them to "it's okay as long as you use them sparingly". I have found that argument to do a lot better with my colleagues...
The same pinball of method calls happens at almost exactly the same way with composition.
You save some idiosyncrasies around the meaning of the object pointer, and that's all.
What if you are actually dealing with state and control-flow complexity. I'm curious what would be the "ideal" way to do this in your view. I am trying to implement a navigation system stripping interface design and all the application logic, even at this level it can get pretty complicated.
Closer to the "ideal": declarative approaches, pure functions, data-oriented pipelines, logic programming.
On the flip side, if the author didn't want to let me do that, I really appreciate having the ability to do it anyways, even if it means tighter coupling for that one part.
With interface-inheritance, each method is providing two interfaces with one single possible usage pattern: to be called by client code, but implemented by a subclass.
With implementation-inheritance, suddenly, you have any of the following possibilities for how a given method is meant to be used:
(a) called by client code, implemented by subclass (as with interface-inheritance) (b) called by client code, implemented by superclass (e.g.: template method) (c) called by subclass, implemented by superclass (e.g.: utility methods) (d) called by superclass, implemented by subclass (e.g.: template's helper methods)
And these cases inevitably bleed into each other. For example, default methods mix (a) and (b), and mixins frequently combine (c) and (b).
Because of the added complexity, you have to carefully design the relationship between the superclass, the subclass, and the client code, making sure to correctly identify which methods should have what visibility (if your language even allows for that level of granularity!). You must carefully document which methods are intended for overriding and which are intended for use by whom.
But the code structure itself in no way documents that complexity. (If we want to talk SOLID, it flies in the face of the Interface Segregation Principle). All these relationships get implicitly crammed into one class that might be better expressed explicitly. Split out the subclassing interface from the superclass and inject it so it can be delegated to -- that's basically what implementation-inheritance is syntactic sugar for anyway and now the complexity can be seen clearly laid out (and maybe mitigated with refactoring).
There is a trade-off in verbosity to be sure, especially at the call site where you might have to explicitly compose objects, but when considering the system complexity as a whole I think it's rarely worth it when composition and a tiny factory function provides the same external benefit without the headache.
These are powerful tools, if used with discipline. But especially in application code interfaces change often and are rarely well-documented. It seems inevitable that if the tool is made available, it will eventually be used to get around some design problem that would have required a more in-depth refactor otherwise -- a refactor more costly in the short-term but resulting in more maintainable code.
I used to do a talk about Liskov that included the joke “CLU didn’t support object inheritance. The reason for this is that Barbara Liskov was smarter than Bjarne Stroustrup.”
Oh the damage that language has done to a generation, but at least it is largely passed us now.
MI is not an issue in c++, and if it were the solution would be virtual inheritance.
People need to look at a playing deck. 52 cards, and you get 8×10^67 possible orders of the deck. Don’t replicate this in code.
I needed it!
For reasons.
Good reasons? No… but I had my justification.
What does this mean? There doesn't seem to be a popular alternative to C++ yet, unfortunately.
Game dev world still has tons of C++, but also plenty of C#, I guess.
Agreed that it’s not really behind us though. Even if Rust gets used for 100% of C++’s typical domains going forward (and it’s a bit more complicated than that), there’s tens? hundreds? of millions (or maybe billions?) of lines of working C++ code out there in the wild that’ll need maintained for quite a long time - likely order decades.
https://security.googleblog.com/2025/11/rust-in-android-move...
http://mail.python.org/pipermail/python-dev/2002-October/029...
Let me give you just one example of Python's stupid implementation of inheritance.
In Python you can initialize a class with a constructor that's not even in the inheritance chain (sorry, inheritance tree because Python developers think multiple inheritance is a good idea).
class A:
def __init__(self):
self.prop = 1
class B:
def __init__(self):
self.prop = 2
class C(A):
def __init__(self):
B.__init__(self)
c = C()
print(c.prop) # 2, no problem boss
And before you say "but no one does that", no, I've see that myself. Imagine you have a class that inherits from SteelMan but calls StealMan in it's constructor and Python's like "looks good to me".I've seen horrors you people can't imagine.
* I've seen superclass constructors called multiple times.
* I've seen constructors called out of order.
* I've seen intentional skipping of constructors (with comments saying "we have to do this because blah blah blah)
* I've seen intentional skipping of your parent's constructor and instead calling your grandparent's constructor.
* And worst of all, calling constructors which aren't even in your inheritance chain.
And before you say "but that's just a dumb thing to do", that's the exact criticism of JS/C++. If you don't use any of the footguns of JS/C++, then they're flawless too.
Python developers would say "Hurr durr, did you know that if you add a object and an array in JS you get a boolean?", completely ignoring that that's a dumb thing to do, but Python developers will call superclass constructors that don't even belong to them and think nothing of it.
------------------------------
Oh, bonus point. I've see people creating a second constructor by calling `object.__new__(C)` instead of `C()` to avoid calling `C.__init__`. I didn't even know it was possible to construct an object while skipping its constructor, but dumb people know this and they use it.
Yes, instead of putting an if condition in the constructor Python developers in the wild, people who walk among us, who put their pants on one leg at a time like the rest of us, will call `object.__new__(C)` to construct a `C` object.
def init_c():
c2 = object.__new__(C)
c2.prop2 = 'three'
print(c2.__dict__, type(c2)) # {'prop2': 'three'} <class '__main__.C'>
And Python developers will look at this and say "Wow, Python is so flawless".The Liskov substitute principle in that context pretty much falls out naturally. As the entire point is to substitute in types into your generic data structure.
It is true that an interface defines certain requirements of things that claim to implement it, but merely having an interface lacks the critical essence of the LSP. The LSP is not merely a banal statement that "a thing that claims to implement an interface ought to actually implement it". It is richer and more subtle than that, though perhaps from an academic perspective, still fairly basic. In the real world a lot of code technically violates it in one way or another, though.
It might be argued that CLU is no better than typical OO languages in supporting the principle, but the principle is still valid - and it was particularly relevant at the time Liskov proposed it, as inheritance was frequently being abused as just a shortcut to do composition (fortunately, things are better now, right?)
I have some data types (structs or objects), that I want to serialize, persist, and that they have some common attributes of behaviors.
In swift I can have each object to conform to Hashable, Identifiable, Codabele, etc etc... and keep repeating the same stuff over and over, or just create a base DataObject, and have the specific data object inherit it and just .
In swift you can do it by both protocols, (and extensions of them), but after a while they start looking exactly like object inheritance, and nothing like commposition.
Composition was preferred when many other languages didn't support object oriented out the gate (think Ada, Lua, etc), and tooling (IDEs) were primitive, but almost all modern languages do support it, and the tooling in insanely great.
Composition is great when you have behaviour that can be widely different, depending on runtime conditions. But, when you keep repeating yourself over and over by adopting the same protocols, perhaps you need some inheritance.
The one negative of inheretance is that when you change some behaviour of a parent class, you need to do more refactoring as there could be other classes that depend on it. But, again, with today's IDEs and tooling, that is a lot easier.
TLDR: Composition was preferred in a world where the languages didn't suport propper object inheretance out of the gate, and tooling and IDEs were still rudemmentary.
But then if you need a DataObject with an extra field, suddenly you need to re-implement serialization and deserialization. This only saves time across classes with exactly the same fields.
I'd argue that the proper tool for recursively implementing behaviours like `Eq`, `Hashable`, or `(De)Serialize` are decorator macros, e.g. Java annotations, Rust's `derive`, or Swift's attached macros.
> The one negative of inheretance is that when you change some behaviour of a parent class, you need to do more refactoring as there could be other classes that depend on it. But, again, with today's IDEs and tooling, that is a lot easier.
It is widely known as the "unstable base class" problem.Another one is, that there are cases, where hierarchies simply don't work well. Platypus cases.
Another one is, that inheritance hides where stuff is actually implemented and it can be tedious to find out when unfamiliar with the code. It is very implicit in nature.
> TLDR: Composition was preferred in a world where the languages didn't suport propper object inheretance out of the gate, and tooling and IDEs were still rudemmentary.
I think this is rather a rewriting of history to fit your narrative.Fact is, that at least one very modern language, that is gaining in popularity, doesn't have any inheritance, and seems to do just fine without it.
Many people still go about "solving" problems by making every noun a class, which is, frankly, a ridiculous methodology of not wanting to think much. This kind of has been addressed by Casey Muratori, who formulated it approximately like this: Making 1-to-1 mappings of things/hierarchies to hierarchies of classes/objects in the code. (https://inv.nadeko.net/watch?v=wo84LFzx5nI) This kind of representing things in the code has the programmer frequently adjusting the code and adding more specializations to it.
One silly example of this is the ever popular but terrible example of making "Car" a class and then subclassing that with various types of cars and then those by brands of cars etc. New brand of car appears on the market? Need to touch the code. New type of car? Need to touch the code. Something about regulations about what every car needs to have changes? Need to touch the code. This is exactly how it shouldn't be. Instead, one should be thinking of underlying concepts and how they could be represented so that they can either already deal with changes, or can be configured from configuration files and do not depend on the programmer adding yet another class.
Composition over inheritance is actually something, that people realized after the widespread over-use of inheritance, not the other way around, and not because of language deficiencies either. The problems with inheritance are not merely previously bad IDE or editor support. The problems are, that in some cases it is bad design.
It Depends™.
Composition can add a lot of complexity to a design, and give bugs a lot more corners to hide in, but inheritance can be such a clumsy tool, that it just shouldn't be used for some tasks.
That goes for almost everything in software. Becoming zealous about "The Only Correct Way" can be quite destructive.
I'm not saying it's malpractice to use inheritance or anything, but it's a tool I definitely hesitate to reach for. Go and Rust removed inheritance entirely, and I'd say those languages are better-off without it.
I also saw why it fell from grace, but I already knew, by then, that it was no panacea. I learned, on my own, that composition was often a better pattern, and I learned that, back in the 1980s.
Not worth arguing about, but I do find absolutism to be almost offensive, and there’s a damn lot of that, in software development.
The problems with bad design don't go away, they're just hidden out of plain view by taking away the keywords. Rust's solution is more powerful, but also leads to more unreadably dense code.
One clear example of this is UI libraries. Most UI libraries have some kind of inheritance structure in OO languages, but Rust doesn't have that capability. The end result is that you often end up with library-specific macros, a billion `derive`s, or some other form of code generation to copy/paste common implementations. Alternatively, Rust code just reuses C(++) code that needs some horrific unsafe{} pointer glue to force an inheritance shaped block down a trait shaped hole.
> Rust's solution is more powerful, but also leads to more unreadably dense code.
Instead of reflection, Rust does serialization with code generation. Java does this too sometimes in libraries like Lombok. The generated code is probably quite dense, but I expect the Java standard library reflection-based serialization code is also quite dense. In both cases, you don't have to read it. `extends Serializable` and `#[derive(Serializable)]` are both equally short. And the generated code for protobuf serialization (which I have read) is pretty readable.
I haven't intentionslly used inheritance in forever, only in cases where some lib forces you to use it that way. Not cause of some trend, but it's just not something you naturally need.
¿Por qué no los dos?
https://h2.jaguarpaw.co.uk/posts/thought-terminating-cliches...
I think the biggest "mistake" in object-oriented programming is the explanations by analogy that many people advocate. A lot of times, people attempt to use a taxonomic metaphor like the tree of life—"a dog is-a mammal" sort of stuff. As a model it falls apart because even the real world tree of life is a flawed model that doesn't fully capture the complexity of life in the way most lay people assume it does. Try getting a random person to justify a platypus being a mammal. Without specific training in biology they stumble. And most computer scientists attempting to employ this analogy are definitely broadly ignorant about biology. You can see it because a lot of the examples people employ aren't even consistent with the metaphor. You're just as likely to see people say things like, "A dog is-a four-legged animal". I think it's an extremely harmful didactic path down which to start.
A lot of these problems happen because most people don't have a good handle on graph theory. They don't understand when they are trying to force a graph with cycles into a tree. Trees are easy for people to understand and handle, graphs with their pesky cycles are much harder, so I get the appeal. But what people come to call "tech debt" or "degenerate edge cases" are really evidence that an inappropriate model was employed early in development.
In real world examples, you'll see object oriented programming and functional programming as well as inheritance and composition used extensively and successfully. I think GUI libraries are a good example here. Buttons and text boxes both inherit from a control base class. This pattern is pervasive and long standing. But you naturally shouldn't usually[1] try to make a form inherit from control as they are much more appropriately compositions of controls.
[1] I say "shouldn't usually" here because some common subforms can be useful encapsulated as a control for composition into other forms, e.g. an address entry form embedded into a user profile form.
Objects and inheritance are good when you need big contracts. Functions are good when you want small contracts. Sometimes you want big contracts. Sometimes you want small contracts.
Sometimes the right answer is to mix and match.
So then I start thinking in less-useful, more abstract definitions, like "inheritance is vertical, composition is horizontal", but of course that doesn't really mean anything.
And at some point, it seems like I just end up defining "composition" to mean "gluing together in a way that's not inheritance". Again, not really a useful definition.
> As a rule, I've always viewed "composition" as "gluing together things that don't know necessarily know about each other"
The extension to this definition given the context of Monoids would be "combining two things of the same type such that they produce a new thing of the same type". The most trivial example of this is adding integers, but a more practical example is function composition where two functions can be combined to create a new function. You can also think of an abstraction that let's you combine two web components to create a new one, combining two AI agents to make a new one, etc.
> "inheritance is vertical, composition is horizontal", but of course that doesn't really mean anything.
This can actually be clearly defined, what you're hinting at is the distinction between sum types and product types. The latter of which describes inheritance. The problem with restricting yourself to only product types is that you can only add things to an existing thing, but in real life that rarely makes sense, and you will find yourself backed into a corner. Sum types let you have much more flexibility, which in turn make it easier to implement truly composable systems.
For example, a channel-based system like what Go or Clojure has; to me that is pretty clearly "composition", but I'm not 100% sure how you'd fully express something like that with categories; you could use something like a continuation monad but I think that loses a bit because the actual "channel" object has separate intrinsic value.
In Clojure, there's a "compose" function `comp` [1], which is regular `f(g(x))` composition, but lets suppose instead I had functions `f` and `g` running in separate threads and they synchronize on a channel (using core.async)? Is that still composition? There are two different things that can result in a very similar output, and both of which are considered by some to be composition. So which one of these should I "prefer" instead of inheritance?
Of course this is the realm of Pi Calculus or CSP if you want to go into theory, but I'm saying that I don't think that there's a "one definition to rule them all" for composition.
The notion of `f` producing a lazy sequence of values, `g` consuming them, and possibly that construct getting built up into some closed set of structures - (e.g. sequences, or trees, or if you like dags).
I've only read a smattering of Pi theory, but if I remember correctly it concerns itself more with the behaviour of `f` and `g`, and more generally bridging between local behavioural descriptions of components like `f` and `g` and the global behaviour of a heterogeneous system that is composed of some arbitrary graph of those sending messages to each other.
I'm getting a bit beyond my depth here, but it feels like Pi theory leans more towards operational semantics for reasoning about asynchronicity and something like category theory / monads / arrows and related concepts lean more towards reasoning about combinatorial algebras of computational models.
But there are other compositions. In particular, for something like process connection, the language of arrows or Cartesian categories is appropriate to model the choices. The actual implementation is another story
In general when you want to model something you first need to decide on the objects and then you need to decide on the relations between those objects. Inheritance is one and there's no need for it to be treated specially. You will find though that very objects actually fit any model of inheritance while many have obvious algebras that are more natural to use
The thing composition does differently is to prevent the effects of the software you're depending on from bleeding further downstream and to make it more explicit which features of the code you're using you actually care about.
Inheritance has a place, but IME that place is far from any code I'm going to be shackled to maintaining. It's a sometimes-necessary evil rather than a go-to pattern (or, in some people's books, that would make it a pattern like "go-to").
One of the most damaging things is when they teach inheritance like "a Circle is a Shape, a Rectangle is a Shape, a Square is a Rectangle" kind of thing. The problem is the real world is exceedingly rarely truly hierarchical. Too many people see inheritance as a way to model their domain, and this is doomed to failure.
Where it works is when you invent the hierarchy. Like a GUI toolkit or games. It's hierarchical because you made it hierarchical. In my experience the applications where it really works you can count on one hand, whereas the vast majority of code written is business software for which it doesn't really.
I could compose functions together like the Haskell `.`, which does the regular f(g(x)), and I don't think anyone disputes that that is composition, but suppose I have an Erlang-style message passing system between two processes? This is still gluing stuff together in a way that is not inheritance, but it's very different than Haskell's `.`.
class Dog : Animal; // inheritance
class Car:
Wheels wheels; // compositionIt's that broader version of composition—particularly in its extreme realization, delegation—that underlies a lot of the behavioral patterns in the book. For example, the State and Strategy patterns boil down to "this object relies on another object to fill in the behavior here, and there are ways to choose what that other object is", which is something it's easy to arrange with subclassing and the only point of the pattern is to avoid subclassing.
class Foo(internal val _list: MutableList<Int>=mutableListOf()): MutableList<Int> by _list { ... }
Here Foo has a _list property that it delegates the implementation of list operations to. You can even do function overrides in the class and interact with the delegate via the _list property. However, messing with internal list state is off limits (a problem with inheritance). val foo = Foo()
foo.add(1)
Like Java, Kotlin supports single class inheritance. But this provides a way out.When I was researching this stuff in the nineties, I came across some papers about role based programming by a Norwegian called Trygve Reenskaug. That formed a lot of my thinking on this topic a bit.
Modern Kotlin and Java look a lot like what he proposed: small interfaces (roles) and classes that implement multiple of these things whose objects can play those roles in different contexts. Go's duck typing (having the operations means it implements the interface) is also cool for this. Traits, mixins, etc. are all variations on this topic that you can find in other languages. Javascript is actually a really interesting languages since it is a prototype based language (inspired by a long forgotten language called Self). It did not have classes for a long time (that's a recent syntactic addition) and you create new objects by copying old ones. And since it is dynamically typed, it has no need for interfaces either.
[1]I know only of some programming languages that even call it roles.
To be honest I always get confused by the difference between interfaces and roles. For me it was always something like an interface/behavior that can be mixed in at runtime.
Since COM only allows for interface inheritance, unlike SOM from OS/2 which also did classes, the way to avoid doing from scratch all members, is to compose and delegate all unmodified methods, while implementing only the new ones in an extended interface.
MFC, ATL, VB and Delphi provided some mechanisms to make this easier, naturally not at the same level as easyness done by Kotlin.
By the way, the same concept is available in Groovy, with @Delegate annotation.
When you inherit from a parent class, you have to be careful to only override methods in ways that the parent expects, so the parent's invariants aren't broken². There's a whole additional set of keywords (private/protected/final) meant to express these parent-child contracts. With interfaces + composition, those are unnecessary: You can compose an object and use it however you want; then, if you want the wrapper object to uphold the inner object's contract, you can additionally implement an interface to formalize that. The behaviours you use and the polymorphic guarantees you make are totally separate.
Inheritance mixes these ideas together and ends up worse for it. Not only the modern approach is simpler, it's more powerful: (1) Polymorphic extension (i.e. extending a polymorphic parent class at runtime) is doable, and (2) multiple inheritance is a non-issue.
[1]: I call it "modern" because newer languages like Go and Rust have eliminated inheritance in favour of exclusively using interfaces/traits.
[2]: See the fragile base class problem.
Smalltalk protocols and message categories were a step toward this (for example you could classify messages as implementing a particular interface, such as the collection or stream protocols), but Smalltalk lacked the type and interface checking supported by Java and other languages.
That was the project that I turned against inheritance, it was 2009, project was written in Java 1.4
GPUI is a great example of the insane amount of boilerplate needed to create a component when you don't have inheritance.
My guess is that people don't create a lot of individual components in this framework to handle different business cases, and instead overload a single text input component with a million different options. I would hate to untangle a mature app written under those conditions.
In "inheritance", it often feels like the programmer's mindset is static, along the lines of "here is a deep relationship that I discovered between 2 seemingly unrelated types", which ends up being frozen in time. For example, a later developer might want to make a subtle innovation to the base type; it can be quite frightening to see how this flows though the "derived" types without any explicit indiction.
Of course, YMMV, but I think of "composition" as "support change" and "inheritance" as "we found the 'correct way to think about this' and changes can be quite difficult".
Since I think that the key to building large systems handling complex requirements is 'how do we support disciplined change in the future' (empowering intellectual contributions by later generations of developers rather than just drudge maintenance).
it's mentally satisfying to create a beautiful class hierarchy that perfectly compresses the logic with no repetition, but i think long term readability, maintainability and extensibility are much better when inheritance is avoided in favor of flat interfaces. (also easier to turn into rpcs as all the overcomplicated object rpc things of the 90s were put to bed).
While in theory it should be straightforward to ship instance state over a wire, in practice most languages have no built-in support for it (or the support is extremely poor in the general case; I remember my first experiments with trying to ship raw Java objects over the wire using the standard library tools back in the early 2000s, and boy was that incredibly inefficient). Additionally, the ability to attach arbitrary methods to instances in some languages really complicates the story, and I think fundamentally people are coming around to the idea that the wire itself is something you have to be able to inspect and debug so being able to understand the structure in transit on the wire is extremely important.
Classes and their inheritance rules make exactly the wrong things implicit for this use case.
That said, I think this is also a good way to approach framing things. Agreed that the idea of "prefer composition" is often a thought termination trick. Instead, try them both! The entire point of preferring one technique over the other is that it is felt to give more workable solutions. If you don't even know what the worked solution would look like with the other technique, you should consider trying it. Not with a precommitment that you will make it work; but to see what it illuminates on the ideas.
So, we just need devs to stop trying to be overly clever? I can get behind that, “clever” devs are just awful to work with.
Inheritance is just a more deeply integrated form of composition which puts the inherited parts on equal footing with the new parts.
That reduces certain indirections and frictions, which is sometimes useful when making things out of other things.
There is more typing/boilerplate but when you read the class file you get a full picture of what’s happening rather than some parts happening automatically in a different file.
I like to say that code should be written with a reader bias: the singular writer should do more work if it makes the class more obvious for the multitude of readers. I feel like composition is a good example of that.
Considering sets, if something is, in set terms a specific subset with a defining membership or characteristic of a definable superset, representing that at compile time effects a hard constraint which honours the set Venn diagram.
If that set/subset constraint doesn't exist then you have to ask yourself if applying a compile time constraint is appropriate.
It does have actual benefits if you can limit its usage, and don't use the full insanity that languages like C++.
I generally dismis people that tell you to always use composition over inheritance without first understanding the problem space, and how it could be modeled.
Composition is not an opposite to inheritance. An opposite would be something like:
Message A ( ... ):
Type B: { ... }
Type C: { ... }
Or, if the body of the method is same ("a parent method"): Type B, Type C:
Message A ( ... ): { ... }
Here we do not give A and B places in the hierarchy but merely say they respond to the same message or that even the procedure is same.I do not know if any meaningful and systematic alternative to a hierarchical way exists in any programming notations. Interface spec is a partial way, but that's all. (I know only a few notations, of course).
Folders are hierarchical way of organizing, akin to inheritance and tags are compositional way of organizing.
I'm kind of waiting for any language to invent some sort of #hashtag interfaces to define contracts :)
The fundamental idea is that of Abstraction which can be defined as the discovery/invention of "higher-level concepts" from more primitive "lower-level concepts" and then reasoning and manipulating at the higher-level. This abstraction is based on structure and/or behavioural attributes.
In order to manage the complexity inherent in the building of large systems certain fundamental aspects were identified as highly desirable. They are Separation-Of-Concerns, Modularization, Reuse and Information-Hiding.
The crucial point to understand is that Abstraction does not imply any of the above aspects! A good example are Mathematical Abstractions. But because for Software we desire the above aspects for our system-as-a-whole we learn to combine them with our Abstractions. This is why we have so many different styles of Programming (i.e. Imperative/OO/Functional/Logic/etc.).
Viewed in the above light the relation between Inheritance and Composition becomes clear. They are just different ways of emphasizing different combinations of the above aspects for your abstractions based on your design needs.
References:
1) Software Fundamentals: Collected Papers by David L. Parnas.
2) Program Development in Java: Abstraction, Specification, and Object-Oriented Design by Barbara Liskov and John Guttag.
3) Multi-Paradigm Design for C++ by James Coplien.
I believe this hints at a major culprit contributing towards the sentiment and use of OO in practice over the years. I'm going to say no people don't. Even if someone goes through education, it won't often require engaging with multiple formative past perspectives at length.. even though there is real value to these musings by comparing and contrasting them altogether first hand.
They seem to not understand that nothing in Software Engineering is a definite law but are simply reasonings based on empirical deductions resulting in agreed upon principles/heuristics. Thus meta-principles drive abstractions resulting in concepts which are then expressed via language features. Now, a language feature expresses only those aspects of the fundamental concept that its designer decided as "correct" (i.e. his/her perspective) which is never its full generality eg. Inheritance expression in various languages. So people need to ask themselves "What is the fundamental concept that i am trying to express via this feature?" and slowly work upwards from specific features to general concepts to even more general meta-principles.
You can have players and monsters, which are all types of "characters" or "units", which is inheritance, but instead of having a separate FlyingPlayer and a separate FlyingMonster, which use the same code for flight, you could have a FlyingComponent, which is composition.
I've been going all in on composition and it's amazing for quickly implementing new gameplay ideas. For example, instead of a monolithic `Player` class you could have a `PlayerControlComponent` then you can move that between different characters to let the player control monsters, drones, etc.
Imagine instead of only Pac-Man being able to eat the pills, you could also give the ghosts the `PillEaterComponent` in some crazy special game modes :)
I've also been fantasizing about a hypothetical language that is built from the ground up for coding gameplay, that doesn't use the word "class" at all but something else that could be a hybrid of inheritance+composition.
Would be nice if something like Swift's "Protocols" could be used in a more dynamic way, at the code level.
With C++, no-one needs to be told (even if good advice) to "favor composition over inheritance" - I think most people who have worked with the language for long enough on large enough projects will end up realizing for themselves that this is generally the preferred approach. Inheritance is a specialized tool, best reserved for specialized use cases.
It's a bit of a shame that C++ "Concepts" were never adopted, or some other type of compile-time polymorphism, since I think this is often all that is really wanted - a compile time guarantee that two classes will provide the same interface, without forcing them to be related by inheritance.
Of course, developers mix and match depending on what the situation calls for. But knowing how these two mindsets differ can make it easier to build code that stays clean and easy to evolve.
And as programming continues to pull ideas from functional, reactive, and declarative styles, the compositional way of thinking will probably stay right at the heart of how we approach object-oriented design.
https://d1gesto.blogspot.com/2025/05/the-split-in-oop-compos...
First-class procedures/functions are a form of composition. Requiring a function type behaves like requiring an interface/class type with only one method. (In languages like F#, `Func<_,_>` is literally defined internally as an abstract class with one method, `Invoke`, although there are other mechanisms to auto-inline lambdas when enough static information is available to do so.) In either case, you can place it into a field of an object or data structure, or pass it directly as an argument to a function/method.
Inheritance might be OK for formally finite domains but I can’t envision other cases where it should be favored.
But then comes an aqua-plane and it breaks your inheritance tree!
But with multiple inheritance is the most natural thing to have a plane that is also a boat and a car.
In Eiffel we favor the appropriate tool that better represents the world.
The reason the aqua-plane broke the inheritance tree is because the modeling is being done backwards.
Objects should be defined by behaviour first and only incidentally contain whatever state is required to support that behaviour.
A well designed object is much more similar to a closure than it is to a data structure.
These metaphors used to teach OOP back in the day seemed appealing but never proved their worth in actual software design and implementation.
Oop is a mistake. Rust and pythons explicit self passing and turning of the dot operator into simple syntactic sugar is the correct approach. We should just stop teaching everything related to this in universities and go back to fundamentals.
Modularization was the core principle of DDD and it still holds up 20 years later.
That's a thought-terminating cliché. The argument against inheritance has been laid out pretty clearly. It's reasonable to rebut that argument. It's not reasonable to say, "you shouldn't criticize inheritance because Everything Has Its Place." Everything does not have its place. Sometimes we discover that something is harmful and we just stop using it.
I was not talking about criticizing. Valid critique us useful and deserved. And this concerns composition as well as any other area. I was talking about crusades by programmers.
And that is not remotely the case here. So yeah, there are many paradigms and each has its place.
Isn't it? People have written extensively about why we should prefer composition to inheritance, and you haven't mounted any defence of inheritance beyond the thought-terminating cliché that it "has its place."
I’m for encouraging best practice, but most things do have its place. I present to this court two examples:“premature optimisation is root of all evil” and “goto statement considered harmful”.
Both well accepted as things should be avoided for good reasons (incl. but not limited to, preserving sanity of coworkers)
But both definitely “have its place”. First one’s place is legitimized (with nuance) by author himself in second part of same sentence. The latter one (goto) is routinely used by linux devs (random example: https://github.com/torvalds/linux/blob/master/fs/ext4/balloc...)
> we just stop using it. We minimise/restrict the usage.
If you're adding a device for navigation that could be used by other things, go for composition.
Is-a Winged, TurbinePowered, Piloted, Aircraft, etc
"Single responsibility" isn't an especially useful yardstick. If you actually need to decompose a complex piece of logic into modules, the place to start is by identifying areas of high cohesion and separating them into loosely coupled functions. Ideally you can match those up to a DDD-style ubiquitous language, so your code will make intuitive sense to people familiar with the domain. "Does this have one responsibility?" really isn't the right question to ask.
The open-closed principle is straight-up wrong. Code should be easy to modify and easy to delete, and you only rarely need to add hooks for extensibility. Liskov substitution is fine, but it has more to do with correctness than cleanliness. Dependency inversion is a source of premature abstraction—you shouldn't open the door to polymorphism until you need to. Interface segregation is good, though.
In general, I think SOLID is overly enamoured with the features of object orientation. Objects themselves just aren't that big of a deal. It'd be like making the whole acronym about if-statements. If I were going to make a pithy acronym about legible code, it'd have more to say about statelessness, coupling, and unit tests. It'd reference Ousterhout's idea of deep modules, and maybe say something about "Parse, don't validate," or at least something against null values.
> "Does this have one responsibility?" really isn't the right question to ask.
It’s a great question to ask. As a senior engineer, the answer might be “no”, but there’s a vast difference between code where the answer is “no” because someone made a conscious choice, vs code where nobody even asked the question. Here’s the thing: a compiler and linker can join ten classes into a single executable, but even a senior engineer cannot look at a single class with ten responsibilities and figure out what the fuck is going on. There’s a doc at my company that describes the core function of one particular service. The doc describes the simplest of systems and so you would be surprised to learn that 1) it took me two years of working one the product before I could write it and 2) nobody knew. The reason it took two years was because there were 10 different pathways, and every pathway was just a giant implementation, each written differently, and each, ultimately, doing the exact same fucking thing. But you’d never be sure just by looking at the code. In fact it very much looked like each of these things had very specific things that they did differently. Over two years, while also doing my job of keeping this thing running and adding features, I refactored the thing to be SOLID. In doing so, demonstrated that they all do the exact same thing. We haven’t finished refactoring everything, but we do now test all the pathways with a parallel implementation that verifies 80 classes and 500 instances at runtime with one class and ten instances.
I work on software that you and most people on planet earth with at least a mobile phone are using in one way or another. I have made many pieces of this system better by evolving a clusterfuck of cohesion into a system that is easy to reason about, maintain and evolve - by apply SOLID principles.
I’m currently working on a package used by over 1,000 services. The most pain has been caused by previous iterations ignoring the open-closed principle. As you say, “easy to modify and delete”. A stronger rule, which perhaps you’re alluding to, is don’t allow any extension at all, and just expose only interfaces. In that sense I could agree open-closed principal is moot, but it’s moot for taking its argument to the logical conclusion.
I am also a fan of DDD, and for the reasons you allude to: the second half of the book is more about communicating in a large engineering organization.
Definitely! :D
Re: SRP, my issue is that it's too subjective. Even for a very simple code snippet like `foo.x = bar.x`, it's not clear whether this covers one responsibility (copying bar's x to foo) or two responsibilities (retrieving bar's x and then setting foo's x). An experienced programmer has enough intuition to understand which of these options is better based on context, but SRP is supposed to be guidance for novices. Maybe I'm asking too much from a one-sentence piece of advice, but maybe splitting up code well requires more than one sentence worth of guidance, and I think SRP boils things down beyond the point of usefulness.
SOLID was invented by Bob Martin, and one of my issues with Martin's style is that he breaks his code into pieces which are far too small. He likes to write methods which are only 2 or 3 lines. Clearly this feels to him like the natural size for a "single responsibility," but to me, he's splitting up highly cohesive code into a profusion of tightly-coupled micro-functions, and I find the result barely legible. This, more than anything, has convinced me that the "one responsibility per function" guideline is just too flexible to be useful on its own.
> I have made many pieces of this system better by evolving a clusterfuck of cohesion into a system that is easy to reason about, maintain and evolve - by apply SOLID principles.
SOLID can describe good code (at least to some degree), but I don't think it's very good at at explaining how to improve code. You're an experienced engineer with good intuition: You see a piece of bad code, you know in your gut what it needs to be changed, and then the final product ends up being SOLID. But if you show the bad code to a junior developer and tell them only, "make it SOLID," I think they'll be lost. They don't have the instincts that tell them whether it's more appropriate to describe a method as having one responsibility or two, or whether they've split things up too much.
> In that sense I could agree open-closed principal is moot, but it’s moot for taking its argument to the logical conclusion.
I'm not sure I follow. My point is that, rather than writing `Foo` in such a way that it's easy to write `FooWithLogging extends Foo`, it should be written in such a way that it's simple to throw away the original `Foo` and write a new version that has logging built in. If you're always extending Foo through inheritance, you end up with a whole string of Foo variants, each piling new features haphazardly upon its parent. Conversely, if you're willing to go back to the drawing board for every new feature, you can evolve a sensible architecture to accommodate any number of features. Of course, if your library has a lot of customers with highly divergent needs, it might be worth building for extensibility, but I don't think that should be the default strategy.
> The most pain has been caused by previous iterations ignoring the open-closed principle.
How so? Injecting new features without adjusting the surrounding architecture to accommodate them naturally? I agree that's a problem, but I feel like extension-by-default also leads to this, since it doesn't give you the opportunity to adjust the original implementation.