Hierarchies of GUI widgets are a good fit. A base View class. Control inherits from that. Button and TextArea inherit from that. Checkbox inherits from Button, and so on. The developer can make a custom Button by subclassing and overriding just a few methods, keeping the rest.
This is similar to the pattern I've found, I heavily lean toward composition for most things but when writing UI tests I use the page object model with a heirarchy that maps the parents classes to the more universal components
So like a navbar if always present would be on the top level parent
And then everything breaks because marketing asks for a version of an existing page, just without the header or navigation, but they do want to keep the footer.
Only when the problem domain is actually a hierarchical system which clearly maps onto an inheritance hierarchy. The best example of a good use of inheritance is CSS
if you think about CSS’s cascading behavior as inheritance, youre going to have a bad time. Despite having “inherit” be a (IME rarely used) keyword, its not meant to be proper “inheritance”
"Proper" inheritance a la Java and C++ is almost always the wrong choice, and never should have become nearly as common as it is. CSS's cascading behavior, even though it works differently, definitely does still use "basing an object or class upon another object or class, retaining similar implementation" (Wikipedia's definition of inheritance), and represents one of the few decent applications of the concept.
CSS inheritance is a freakin nightmare. People complain about C++ class inheriting from a few other classes, but for the worst I've seen - Angular with Material - open up practically anything in devtools and you see an absolutely ridiculous hierarchy of derivations. It's so far beyond what you have to deal with with C++ that comparison is pointless.
Inheritance is a deliberate design choice that imposes stricter "rules" on your objects than simply using composition.
Composition is favoured over inheritance because it provides looser coupling and better encapsulation for example.
With parent child hierarchies, you will find that if you change the parent it'll probably break the children because they assumed certain things would be inherited.
And if you find yourself checking if the object is an instance of a specific child class because the child provides additional methods or properties that the parent doesn't have, that's also a bit weird.
There are many cases where both inheritance and composition are valid solutions, and often times people will just say composition is objectively better without explaining why.
Inheritance is pretty strict, and it's better when you need it to be strict. The moment you try to use workarounds to get around the strict rules, maybe you shouldn't use inheritance.
Virtual methods: it only needs a single virtual table indirect dispatch (composition may need a (long) chain of calls to be polymorphic, but not virtual).
That's how C++ happens to implement them, not what an interface is. Go satisfies interfaces with no inheritance and nothing added to the struct.
That's all implementation detail anyway. What matters is the design: an interface is a contract about what something can do, not a statement about what it is.
I wasn't familiar so I checked how the memory layout of Go interfaces work. Here's what I found.
If a function takes an interface as a parameter, then that parameter's binary layout will be two pointers, one pointer to type metadata which includes a vtable, and one pointer to the concrete value.
When you pass a concrete value to a function that takes an interface, then at runtime Go will construct a new interface object that points to the concrete value, and it will generate and cache a vtable for that concrete type, so that the known method layout of the interface can be mapped to the functions of the concrete type.
The composition vs inheritance question is not about what pointers point where in memory, it’s about how you structure your code so it can evolve over time to adapt to changing business requirements.
I feel like a lot of people in this thread are equating inheritance with polymorphism when I completely agree with you that inheritance is just a code structure tool (and imo not a good one).
It’s fine if you’re using a language or in a codebase where inheritance is used and you follow the idiomatic coding style, but it’s obviously not necessary to achieve polymorphism given languages like go and rust exist.
Inheritance is good when you’re hacking at some code in a dependency you bought in with a package manager and you can’t (or don’t want to) change the upstream code.
If it’s your owned code and architecture the good cases are few and far.
The most helpful, specific, and practical lessons on OOP I've come across have come from the C++ community, and specifically from Bjarne Stroustrup and Herb Sutter:
When to inherit
Good use of inheritance should involve both the strategy and template design patterns. The template pattern is how you would write the guts of the class, and the strategy pattern is how you would use the resulting hierarchy.
A base class should be designed to be inherited from, and for the purpose of offering an interface to a variety of implementations. There can be many ways to implement a cache, for example. Array cache, file cache, local storage cache, proxy cache, memcached cache, and many more we'll dream up in the future. A base class Cache would define the public operations, and possibly also a skeleton of the operations. It would invoke overridable methods that each of the variety of implementations would provide.
Public inheritance is substitutability. Inherit, not to reuse, but to be reused
Public inheritance is indeed about reuse, but not the way many programmers seem to think. The purpose of public inheritance is to implement substitutability. The purpose of public inheritance is not for the derived class to reuse base class code.
The "is-a" description of public inheritance is misunderstood when people use it to draw irrelevant real-world analogies: A square "is-a" rectangle (mathematically) but a Square is not a Rectangle (behaviorally). Consequently, instead of "is-a," we prefer to say "works-like-a" (or, if you prefer, "usable-as-a") to make the description less prone to misunderstanding.
Further reading: Virtuality, from C++ standards committee member Herb Sutter.
Prefer to use Template Method to make the interface stable and nonvirtual, while delegating customizable work to nonpublic virtual functions that are responsible for implementing the customizable behavior. After all, virtual functions are designed to let derived classes customize behavior; it's better to not let publicly derived classes also customize the inherited interface, which is supposed to be consistent.
Note that the base class is now in complete control of its interface and policy, and can enforce interface preconditions and postconditions, insert instrumentation, and do any similar work all in a single convenient reusable place - the nonvirtual interface function. This promotes good class design because it lets the base class enforce the substitutability compliance of derived classes in accord with the Liskov Substitution Principle, to whatever extent enforcement makes sense.
Any time the relation between types is an isA relation, eg. Dog is a Mammal, and Mammal is an Animal.
But even then, you probably can and maybe should rework the model for hasA relations when possible. Dog and Cat are both Mammals, but Dog has a much less restrictive signature on the feed method than Cat, which could be harder to capture with inheritance versus using a Feedable trait.
One thing to always look out for is the SOLID principles, specifically the L part: Liskov Substitution Principle.
For example, in math geometry, every Square is a Rectangle.
That would make it obvious to model them this way as classes, right? Wrong. Or at least "it depends", on what exactly are the defined public methods of Rectangle.
For example, if the Rectangle is created using one corner's coordinates and a&b lengths, that makes no sense for a Square (or at least it will break when you set different a&b lengths). It's not a constraint that would break a Rectangle, so it's a wrong kind of abstraction that breaks the principle.
I recently used inheritance to override a behaviour on connection (we have some custom security steps that were not playing well with the default behaviour). So ig when you want to have a class instance and everything it comes with but slightly tweaked
Some people may say that should be accomplished by traits rather than inheritance, but the question was about inheritance versus composition, and composition does not allow the containing object to be used as a substitute for the thing contained.
In the design of something like a circuit simulator, there should typically be a base component type with the logic necessary to add itself into or remove itself from a circuit, and other component types should derive from that. If one wanted to use a composition relationship, a transistor should be modeled by having an ElectronicComponent class whose CircuitBehavior property owns a TransistorGuts instance, rather than by having the specialized Transistor object own a CircuitComponent object.
Having the specialized component type inherit from the ElectronicComponentBase type has advantages and disadvantages. Separating out the electronic behavior would makes the specialized component classes less sensitive to changes in ElectronicComponent but having them integrated may allow components more ability to interact with the rest of the simulation.
(Incidentally, I wish circuit simulators were used more often as a basis for examples instead of things like animals or vehicles. A circuit simulator is something that would be logically built within an object-oriented framework, unlike something like a car which exists as a physical entity).
As others have mentioned, a third thing which belongs with these two is the idea of traits/interfaces/abstract base classes. This is a form of inheritance in the sense that the external interface is inherited, but internal implementation details are not. There are lots of good use cases for this form of inheritance — in many languages, this is the preferred way to write polymorphic code, although Python tends to lean in favor of duck typing.
The other form of inheritance is when actual variables or implementations of methods are being inherited. This is the thing that should be avoided whenever composition would suffice. Some people will tell you that inheritance models an is-a relationship while composition models a has-a relationship, but those people are wrong (and you should be distrustful of any sort of programming advice which sounds like this — if you find yourself trying to answer metaphysical or ontological questions in order to make decisions about software architecture, you are probably doing something wrong.) I’m not convinced that there are any good use-cases for inheritance of implementation, but I don’t feel like my experience has been broad enough to justify such a sweeping claim.
The whole second paragraph feels like a pretty extreme take without much to back it up other than a different perspective. Particularly "those people are wrong" and "you should be distrustful of any..." are strong opinions.
If it's the "metaphysical" view is bad and these things are really just tools, isn't it best to use a simple and straightforward tool that does the job based on an easily explained mental model? I see a lot of useful abstract base classes that DO inherit implementation details and make a simple contract for extending and using polymorphism to solve problems in (IMO) a natural and intuitive way.
I’ve been burned bad by some hard-to-work-with coworkers, and some frustration was coming out in my answer, but I can be normal. What were the use-cases you had in mind?
Re-reading, I might have misunderstood what you mean by inheritance of internal implementation details. The example might help get on the same page.
I am thinking of things like JsonConverter in C# which define the approximate shape of a mechanism and then you fill in a few specific gaps to apply the concept to a dynamic type. Often in cases like this there is a shared core implementation that uses the abstract parts which might be able to be overwritten but shouldn't be repeated. But, maybe this still counts as one of the examples you said was good?
I'm sure that could be written with composition or traits, but IMO inheritance is a perfectly usable way to handle it.
Generally I found that inheritance should usually represent a "I want to use A as a B" demand, not an "is a" relationship.
As an example: if you have both a customer and an employee in your domain model, you shouldn't derive them from person "because both are a person" (is a customer truly always a person?). Instead look how you want to use them. You probably have a module sending out emails. So you define in that module an email recipient and have both customer and employee inherit from email recipient.
For simple hierarchies that works quite well, for more expansive hierarchies you quickly notice that you have multiple parallel systems, meaning you need multiple inheritance to mirror the external structure which makes everything more complicated.
Other uses where I found inheritance usefull:
When libraries provide a default implementation that I can modify if needed. In the concrete case I needed a commandline parser that throws a specific exception if a parsing error occurred, I was very pleased that the standardlibrary parser had an on_error method that I could overwrite.
Separating some very unsavory parts out. In the concrete example it was an glue programm between an old application that stored dates in different formats in the same column (as strings) so I made a neat little date baseclass and a derived class that dealt with the dependent conversion. Yes they were quite strongly coupled, but less than putting everything into one class.
26
u/dmazzoni 15d ago
Hierarchies of GUI widgets are a good fit. A base View class. Control inherits from that. Button and TextArea inherit from that. Checkbox inherits from Button, and so on. The developer can make a custom Button by subclassing and overriding just a few methods, keeping the rest.
9
u/DanceHackRock 15d ago
Inheritance is more a thing for interfaces not for implementation.
Although it is often taught as the main feature of OOP, it is actually not.
The currently important main feature is inversion of control.
24
u/y0shii3 15d ago
Only when the problem domain is actually a hierarchical system which clearly maps onto an inheritance hierarchy. The best example of a good use of inheritance is CSS
5
u/mxldevs 15d ago
Inheritance is a deliberate design choice that imposes stricter "rules" on your objects than simply using composition.
Composition is favoured over inheritance because it provides looser coupling and better encapsulation for example.
With parent child hierarchies, you will find that if you change the parent it'll probably break the children because they assumed certain things would be inherited.
And if you find yourself checking if the object is an instance of a specific child class because the child provides additional methods or properties that the parent doesn't have, that's also a bit weird.
There are many cases where both inheritance and composition are valid solutions, and often times people will just say composition is objectively better without explaining why.
Inheritance is pretty strict, and it's better when you need it to be strict. The moment you try to use workarounds to get around the strict rules, maybe you shouldn't use inheritance.
4
u/behind-UDFj-39546284 15d ago
Virtual methods: it only needs a single virtual table indirect dispatch (composition may need a (long) chain of calls to be polymorphic, but not virtual).
4
u/BoBoBearDev 15d ago
I only use interface inheritance because I don't want to duplicate the interface signatures.
Other than that, I stopped doing it. I have a processor that process object that implemented interfaces. So, I can swap out processor easily.
8
u/This_Growth2898 15d ago
When you want to use the instances of a derived class in methods/functions that accept a base class.
2
u/violent-calculator 15d ago
Inheritance is good when you’re hacking at some code in a dependency you bought in with a package manager and you can’t (or don’t want to) change the upstream code.
If it’s your owned code and architecture the good cases are few and far.
2
u/tinmanjk 15d ago
template method pattern hasn't been mentioned. also in languages that don't have default implementation for methods on interfaces.
2
u/ChemTechGuy 15d ago
When your parents are rich and your writing skills are only so so
2
u/MoTTs_ 15d ago
The most helpful, specific, and practical lessons on OOP I've come across have come from the C++ community, and specifically from Bjarne Stroustrup and Herb Sutter:
When to inherit
Good use of inheritance should involve both the strategy and template design patterns. The template pattern is how you would write the guts of the class, and the strategy pattern is how you would use the resulting hierarchy.
A base class should be designed to be inherited from, and for the purpose of offering an interface to a variety of implementations. There can be many ways to implement a cache, for example. Array cache, file cache, local storage cache, proxy cache, memcached cache, and many more we'll dream up in the future. A base class Cache would define the public operations, and possibly also a skeleton of the operations. It would invoke overridable methods that each of the variety of implementations would provide.
Further reading: Public inheritance is substitutability, from C++ standards committee member Herb Sutter.
Further reading: Virtuality, from C++ standards committee member Herb Sutter.
5
u/Delta-9- 15d ago
Any time the relation between types is an
isArelation, eg. Dog is a Mammal, and Mammal is an Animal.But even then, you probably can and maybe should rework the model for
hasArelations when possible. Dog and Cat are both Mammals, but Dog has a much less restrictive signature on thefeedmethod than Cat, which could be harder to capture with inheritance versus using a Feedable trait.3
u/relevant_tangent 15d ago
When it's from a rich uncle you didn't know you had
1
u/RedAndBlack1832 15d ago
I recently used inheritance to override a behaviour on connection (we have some custom security steps that were not playing well with the default behaviour). So ig when you want to have a class instance and everything it comes with but slightly tweaked
1
u/ElectrSheep 15d ago
When you need to support polymorphic associations among entities persisted in a relational database with foreign keys.
1
u/8lall0 15d ago
GUI and sometimes game development, otherwise just don't.
1
u/flatfinger 15d ago edited 15d ago
The main case is when substitutability is useful.
Some people may say that should be accomplished by traits rather than inheritance, but the question was about inheritance versus composition, and composition does not allow the containing object to be used as a substitute for the thing contained.
In the design of something like a circuit simulator, there should typically be a base component type with the logic necessary to add itself into or remove itself from a circuit, and other component types should derive from that. If one wanted to use a composition relationship, a transistor should be modeled by having an ElectronicComponent class whose CircuitBehavior property owns a TransistorGuts instance, rather than by having the specialized Transistor object own a CircuitComponent object.
Having the specialized component type inherit from the ElectronicComponentBase type has advantages and disadvantages. Separating out the electronic behavior would makes the specialized component classes less sensitive to changes in ElectronicComponent but having them integrated may allow components more ability to interact with the rest of the simulation.
(Incidentally, I wish circuit simulators were used more often as a basis for examples instead of things like animals or vehicles. A circuit simulator is something that would be logically built within an object-oriented framework, unlike something like a car which exists as a physical entity).
1
u/armahillo 15d ago
Liskov substitution is one good test:
Can the subclass be dropped in to any instance of the parent class being used and still function?
If the child instance cannot function reasonably where its parent would function, then inheritance is probably not the right approach.
1
u/Chroniaro 14d ago
As others have mentioned, a third thing which belongs with these two is the idea of traits/interfaces/abstract base classes. This is a form of inheritance in the sense that the external interface is inherited, but internal implementation details are not. There are lots of good use cases for this form of inheritance — in many languages, this is the preferred way to write polymorphic code, although Python tends to lean in favor of duck typing.
The other form of inheritance is when actual variables or implementations of methods are being inherited. This is the thing that should be avoided whenever composition would suffice. Some people will tell you that inheritance models an is-a relationship while composition models a has-a relationship, but those people are wrong (and you should be distrustful of any sort of programming advice which sounds like this — if you find yourself trying to answer metaphysical or ontological questions in order to make decisions about software architecture, you are probably doing something wrong.) I’m not convinced that there are any good use-cases for inheritance of implementation, but I don’t feel like my experience has been broad enough to justify such a sweeping claim.
1
u/GodOfSunHimself 14d ago
So many bad avices here. The answer is almost never.
1
u/ir_dan 14d ago
When you want a nice mechanism for dynamic dispatch that can scale. That's what inheritance is really for.
1
u/OldWar6125 13d ago
Generally I found that inheritance should usually represent a "I want to use A as a B" demand, not an "is a" relationship.
As an example: if you have both a customer and an employee in your domain model, you shouldn't derive them from person "because both are a person" (is a customer truly always a person?). Instead look how you want to use them. You probably have a module sending out emails. So you define in that module an email recipient and have both customer and employee inherit from email recipient.
For simple hierarchies that works quite well, for more expansive hierarchies you quickly notice that you have multiple parallel systems, meaning you need multiple inheritance to mirror the external structure which makes everything more complicated.
Other uses where I found inheritance usefull:
When libraries provide a default implementation that I can modify if needed. In the concrete case I needed a commandline parser that throws a specific exception if a parsing error occurred, I was very pleased that the standardlibrary parser had an on_error method that I could overwrite.
Separating some very unsavory parts out. In the concrete example it was an glue programm between an old application that stored dates in different formats in the same column (as strings) so I made a neat little date baseclass and a derived class that dealt with the dependent conversion. Yes they were quite strongly coupled, but less than putting everything into one class.
1
u/InterestingYak1525 13d ago
Inheritance is widely used in the Django framework. I like how it is used there.
1
u/z436037 15d ago
It's not. So much so, that over the past 45 years we went from:
* 1980s-1990s: C++ supporting single + multiple inheritance, leading to things like the "diamond problem"
* 1995-2015: Java supporting single inheritance only, but as many interfaces as you like. Led to abominations like SpringFramework and J2EE.
* 2010-present: Golang: no inheritance at all. Everything is composition and interfaces.
0
u/hk4213 15d ago
Provide an example for comparison. I'm sure there are countless good breakdowns of this with the problem you need to solve in mind.
0
u/FunAd6672 15d ago
Use composition when you want to mix and match behaviors without getting locked into a rigid class hierarchy.
0
u/MagicWolfEye 15d ago
Seldom
-1
u/roksah 15d ago
when you don't know if the animal going to be a dog, a cat or human at run time but you want them all to walk
-1
u/whitetiger1208 15d ago
I dont know, ask Claude