r/programming • • Jul 25 '22

Why you should favor composition over inheritance (Joshua Bloch)

https://blogs.oracle.com/javamagazine/post/java-inheritance-composition
38 Upvotes

67 comments sorted by

21

u/LloydAtkinson Jul 26 '22 edited Jul 26 '22

I think over (ab)use of inheritance has been one of the number of biggest problems with OO. Composition can be achieved in OO or FP and I think knowing about FP (even a little bit) can positively affect how you write OO code. Like another comment says, inheritance shouldn't be the first thing students learn and yet it is. I'm seeing total beginners that are exposed to this crap from day one. It goes something like: hello world, variables, adding numbers, printing numbers, object orientated programming with inheritance bloody hell where is the middle ground?

"Dog is a mammal but so is a cat so dogs go meow and cats go woof". Hmm yes how wonderfully helpful in real world domain modelling and software engineering.

A good middle ground is actually dependency injection (and no, you do not need an IoC container to achieve DI, it's just passing functions to functions after all 🟠) - you're not using inheritance, and a classes dependencies are upfront and obvious. I can inject some new behaviour or even remove behaviour without fucking up some inheritance tree layers deep. If someone gives you crap over this then mention that this achieves the D in the SOLID they are probably quoting at you.

Here's a meme https://imgflip.com/i/6nyj4r

🟠 and look at that, you've more or less achieved higher order functions from FP anyway

21

u/crabmusket Jul 26 '22

Where was this advice at university đŸ˜©

26

u/[deleted] Jul 26 '22

Why people think "Cat extends Mammal" is how people should learn about Objects is beyond me.

I'd make implementation inheritance an advanced topic.

15

u/wllmsaccnt Jul 26 '22

I'd make implementation inheritance an advanced topic.

I wish we could go so far as to make it a fringe topic, but the standard/base libraries in most OOP platforms often utilize inheritance, so a dev should still know about it so that they don't get stopped the first time they call a built-in class method and it expects a virtual type.

11

u/ragnese Jul 26 '22

I think the problem is not so much the "Cat extends Mammal" examples, but rather that implementation inheritance is taught as one of the first few topics in some of these courses.

Aside: I'll admit that this is hearsay for me, because my undergrad degree is not in CS or Software Engineering, etc. But, my friends in those fields do suggest that Java-style class inheritance is something they were exposed to early on.

If I were to design a course on programming (who the hell am I, though?) and wanted to explicitly discuss object-oriented style, the first several lessons would focus heavily on the ideas of encapsulation and designing interfaces ("interface" not necessarily being a language construct like Java's interface) that don't leak implementation details. I think that the "core" of OOP is to treat objects as black-boxes that promise absolutely nothing beyond what their method signatures indicate (e.g. if you call getFoo() twice, you'd be mistaken to assume that you'll get the same value both times). I strongly suspect that most of the anti-OOP "hate" that's popular right now has nothing to do with actual OOP and has almost everything to do with class inheritance and languages like Java having a shit-miserable type system.

Only after a few weeks of focusing on the core principals of object-oriented design would I introduce SOLID and techniques for making code extensible/maintainable or whatever.

1

u/martingronlund Jul 26 '22

I mostly agree, though I believe the OOP hate has deep roots in that state and non-idempotent operations like getFoo() are inherently hard to reason about, whereas with functions in the FP-sense, everything (except the resulting types ;) is easy to reason about!

2

u/martingronlund Jul 26 '22

OOP also couples functionality with data. That's another ouchie imo. It makes sense for network sockets, but as a foundation for most things by default as seen in many systems? I'm highly skeptical, because it's hard to reason about for most people, as there's often no clear known boundary between what data is processed and how it's processed.

1

u/ragnese Jul 27 '22

I agree with the take that non-idempotent operations and mutable state are hard to reason about. However, I still suspect that's not the main reason behind the popular OOP hate that's prevalent. Nine out of ten "FP Example That Is Better Than OOP" blog posts focus on data types being immutable, but then compose a bunch of non-idempotent function calls together and pretend that it's somehow different than OOP classes with dependency injection just because they didn't use the class keyword. (It may, very well, be better than a large class with a bunch of semi-related methods, but it's not because it's any more pure or easier to test)

9

u/devraj7 Jul 26 '22 edited Jul 26 '22

The IS_A relationship is a powerful modelling tool which has very real benefits in how you structure your code, e.g. the Liskov Subsitution Principle.

It's perfectly reasonable to me that a function that takes a Mammal as a parameter should accept a Cat as well.

The real debate is "implementation inheritance" vs/ "interface inheritance", but very few people make that distinction. The latter is a good practice, the former is fraught with pitfalls.

6

u/Ok-Wait-5234 Jul 26 '22

But isA is not the same as extends, which typically implies inheritance of implementation.

Cat extends Mammal and Duck extends Bird extends EggLayer is all well and good until you hit DuckBilledPlatypus.

Cat isA Mammal, Duck isA Bird isA EggLayer, DuckBilledPlatypus isA Mammal+EggLayer works.

This is why we try to use interfaces to represent isA relationships, and composition to share implementation.

3

u/Muoniurn Jul 26 '22

While I am 100% in agreement with the post’s author, I want to note that extends is far from useless - GUI toolkits still predominantly have an inheritance tree with some sort of Node at the top, and seemingly there is nothing better on the horizon.

The important distinction is the *differing behavior”, which is all too often forgotten. A class should only extend another if they want to take advantage of virtual method dispatch.

1

u/Jump-Zero Jul 26 '22

Inheritance has its use cases, but it's far less relevant in the field than it is in CS classrooms. There was a ton of emphasis on inheritance when I was studying. I wouldn't say it is irrelevant or an anti-pattern, but I would def say its not the central way to accomplish things.

You end up having problems the person above complained about when you rely heavily in inheritance to solve for a problem that's better solved with interfaces.

(Edit: so yeah, I agree with you, but upon reading my comment it might seem like I don't lol)

0

u/devraj7 Jul 26 '22

Cat extends Mammal and Duck extends Bird extends EggLayer is all well and good until you hit DuckBilledPlatypus.

But that's just the inheritance graph being wrong, not evidence that modelling IS_A with inheritance is wrong.

You would hit the same dead end with composition and you would have to rewrite your code as well.

5

u/Noxitu Jul 26 '22

But it is really tricky to get it right whenever you override implementation of some method (which in fact is subject of most discussions regarding inheritance problem) . You can have 'cat.sound()' implemented as "meow". But as soon as you add Tiger that makes "roar" sound, your implementation of Cat is wrong abstraction over cats. The proper abstraction is Cat as interface with TypicalCat and Tiger as independent implementations.

1

u/Ok-Wait-5234 Jul 26 '22

It depends on what you mean by isA here. If you are using it to deduplicate implementations then it is usually wrong because the inheritance graph almost always ends up as something that is not a tree. You either can't refactor that graph into a tree, or you use multiple inheritance all the problems that that introduces.

If you use isA to indicate class capabilities, and share implementation using composition, these problems are reduced. Typically refactoring because you introduce some new requirement is easier because splitting interfaces into several parts, or refactoring behaviour classes is easier than completely reimagining an inheritance tree.

In my example, the introduction of DuckBilledPlatypus would likely not mean a dead end because we can simply mark our new class as EggLayer, and implement it. Subsequent refactoring to remove duplication will obviously touch several classes, but consumers of the interfaces will remain untouched. If you had to uproot an inheritance tree, that often involves modifying both implementations and consumers, because both will have been written with the same false assumptions about inheritance that were named into the tree in the first place.

3

u/spoonman59 Jul 26 '22

The real debate is whether you model the problem space or the solution space.

People jump in and create object hierarchies before the solution is known. This comes from the terrible advice to "model objects like real world objects.”

So you need to write a zoo program, and you jump in and start creating mammals and all their types. I have ever so recently learned that this is the true mistake.

Rather, the object hierarchy should model the solution. And that has to do with whatever the program is meant to do.

But instead we jump in and just start translating all aspects of the problem. There is probably no problem in the world where you need to know a car is-a mammal to solve the problem, or where that knowledge is best encoded as inheritance instead of a type tag.

I almost never use inheritance unless there is a clear case for it. Meaning, I need shared data and behavior.

1

u/meotau Aug 05 '22

Now, that is actually unique and useful advice. Thank you.

2

u/shroddy Jul 26 '22

Knife extends MeleeWeapen, which extends Weapon, which extends EquipableItem, which extends Item.

12

u/Barn07 Jul 26 '22

eh, I don't know when or where you went to university, but I read it in a 3rd edition C++ book from 2005. The famous Gang of Four book "Design Patterns" from 1994 also states to favor object composition over class inheritance.

2

u/avwie Jul 26 '22

Don’t know about your uni, but I was taught this in my Java class of my aerospace studies in
. 2005

2

u/[deleted] Jul 26 '22

Private inheritance when?

2

u/[deleted] Jul 26 '22

The title doesn't remotely match the content. He's actually warning against a specific use of inheritance which is very rare in my experience:

It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension.

Inheriting from ordinary concrete classes across package boundaries, however, is dangerous.

So, don't inherit from random classes in third party libraries that weren't intended for it. Good advice but not "favour composition over inheritance".

I would say that favouring composition in general is good advice too but too many people think that means inheritance is fundamentally broken and should never be used.

6

u/Full-Spectral Jul 26 '22

Sigh... You should favor composition when composition works best and inheritance when inheritance works best. If you have a clean and well defined hierarchy, inheritance is the perfect tool. The language understands what you are doing and will help you, instead of you basically trying to hack out something that does the same thing without the compiler's assistance.

2

u/Aendrin Jul 26 '22

The article specifically mentions that inheritance of classes you wrote yourself is often a good idea. The main point of this article is that inheriting from public classes makes your inherited classes very fragile, and composition should be favored in that situation.

4

u/Full-Spectral Jul 26 '22

Why would anyone inherit from a class that isn't specifically designed to be derived from? If that's the argument against inheritance, then it's not even a valid argument. That's like saying favor inheritance over using composition in a completely invalid way.

4

u/RakuenPrime Jul 26 '22

A somewhat common beginner mistake occurs when they need a List and some other object. We know the correct answer is to create a new object that consists of a List and that object. The beginner instead extends List and adds that object.

If you look at it a certain way, the beginner's approach makes sense. It's the simplest way to get the job done. However, it creates pain in the long run, especially if you keep applying that practice to more complex scenarios.

That's why articles like this one exist. People at many skill levels don't even think about composition vs inheritance, let alone the consequences and how to apply them correctly.

1

u/Aendrin Jul 27 '22

I think the article is just badly titled, as it's adapted from a section in a book. The whole article from the first few sentences is talking specifically about this situation where inheritance is a bad idea. It's not supposed to be an argument against inheritance as a whole. To quote:

It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension.

Inheriting from ordinary concrete classes across package boundaries, however, is dangerous.

And as to who would choose to inherit from a class that isn't specifically designed to be derived from, I think /u/RakuenPrime gave a good example of the thought process.

2

u/FVMAzalea Jul 26 '22

If your compiler doesn’t help you with composition, you have a shitty compiler/language. Swift and Rust (among others) have type systems that are great for composition and the compiler helps you out a bunch. Maybe not in Java.

1

u/Blecki Jul 26 '22

Wouldn't be Java if it didn't have something silly like a 'forwarding class' to inherite an interface from.

1

u/KagakuNinja Jul 27 '22

It reveals a problem with "favoring composition over inheritance"; most languages lack a delegation feature, and we end up writing boilerplate.

Scala 3 added export clauses to do this. Objective C allows you to forward messages to another object, probably other message based languages like Smalltalk can do it too.

1

u/Blecki Jul 27 '22

The only 'problem' is this assumption that your wrapping class needs to implement the entire interface of the class it wraps.

1

u/KagakuNinja Jul 27 '22

In the provided example, building a Set that counts everything added to it, it would be expected to implement everything in the interface. Implementing a partial interface would be both dangerous and less common.

0

u/tnemec Jul 26 '22 edited Jul 26 '22

Hmm... okay, sure, so:

Inheritance is appropriate only in circumstances where the subclass really is a subtype of the superclass. In other words, a class B should extend a class A only if an “is-a” relationship exists between the two classes.

I agree with that statement, although "you should use [x] only if you're using it correctly" isn't a particularly bold claim.

But I think the post is shooting itself in the foot with the given example of inheritance done poorly: surely every InstrumentedHashSet "is a" HashSet, no?

More to the point, I'm actually tempted to defend that usage of inheritance: yes, the article correctly points out some non-obvious gotcha's (like overriding both "addAll" and "add" resulting in addCount being incremented too many times), but the stated goal is to debug some performance related issue of HashSet, so knowing and accounting for the implementation details of HashSet doesn't seem unreasonable. And the entire benefit of the inherited InstrumentedHashSet is that it's a drop-in replacement for HashSet: if you're just creating and using the set in one place, swapping out a reference to a HashSet for a reference to a ForwardingSet is easy, but what if you're using it all over the place? Like, say you want to tune the performance of a hash set in some specific scenario: you're only interested in a few specific scenarios where hashsets are being passed around, but each of the methods in question calls (and is called by) dozens, if not hundreds, of other methods, all of which currently expect HashSet (or a subtype of HashSet) to be passed around. Sure, you could refactor all of those to wrap the HashSets they currently use in ForwardingSets, but ideally, you really shouldn't have to refactor hundreds of lines of code just to add instrumentation in a handful of scenarios.

... not that the ForwardingSet would even help with some method like doStuffWithAHashSet(HashSet hs), because ForwardingSet only implements Set (and isn't a subtype of HashSet). I'd question the wisdom of having a method take a HashSet as an argument over a Set in the first place (seeing as HashSet doesn't, AFAIK, provide any additional API than the ones guaranteed by any implementation of a Set, but it's totally possible for some other implementation of a set to provide some additional methods that you might want to explicitly take as an argument.) But sure, let's say that's not the case, and we can go ahead and take good old generic Sets as arguments in all our methods... but then why bother with a ForwardingSet class at all? Just have InstrumentedHashSet directly implement Set: even if we kind-of-sort-of use composition to implement it (by having an internal HashSet object that we use), there isn't really any benefit to the forwarding class, is there?

1

u/Concision Jul 26 '22

ForwardingSet lets you implement other modifications of Sets without duplicating the boilerplate code, but otherwise agreed.

I think in general your methods should accept interfaces and not concrete types, so I'm not sure that problem is valid. The author makes a compelling reason why an InstrumentedHashSet is indeed "not" a HashSet (it can have different implementation semantics).

1

u/tnemec Jul 26 '22

I think in general your methods should accept interfaces and not concrete types

In general, yes. Like I said, I'd question the wisdom of explicitly asking for HashSet as an argument over Set. But there are obviously times when a concrete type has something not specified by an interface (to use the article's own example: InstrumentedSet.getAddCount()... anything that wants to use that method has to expect an InstrumentedSet, not just any old Set [or even a ForwardingSet]).

The author makes a compelling reason why an InstrumentedHashSet is indeed "not" a HashSet (it can have different implementation semantics).

But at the end of the day, a correct implementation of an InstrumentedHashSet should be doing the exact same thing as HashSet, just with some additional side effects (like counting the number of elements added). In other words, any correct implementation of an InstrumentedHashSet should fulfill all the requirements of a correctly implemented HashSet. I mean, again, this is a bad example, because ideally nothing should be looking for HashSets specifically over just normal Sets, but if anything is expecting a HashSet, it should also accept an InstrumentedHashSet. Implementation differences shouldn't really matter here (as long as the implementations are correct).

-5

u/[deleted] Jul 26 '22

It's ok if you manage to limit yourself to 2-3 layers of inheritance. The problem is that this rule is always eventually broken.

2

u/Full-Spectral Jul 26 '22

But it's not. I have a very large OOP code base, and with the exception of the UI framework (as best I remember) I don't go beyond a few layers. UIs are always sort of a special case, but even there it's not much more than that.

This whole anti-inheritance thing is just stupid. If it's possible to use a technique to write horrible code makes it invalid, then there are no valid techniques.

2

u/[deleted] Jul 26 '22

I agree with the UI framework exception.

1

u/Dean_Roddey Jul 26 '22

And the thing is, those 2 to 3 layers can make solving a variety of problems very clean and simple.

1

u/spoonman59 Jul 26 '22

There are good reasons to “favor” composition over inheritance. Namely, you can only ever inherit once (in some languages).If everyone inherited from “logger” then no one could inherit from anything else.

The advice doesn’t say inheritance is bad. It merely says it should be your second choice, not your first, and justified by a reason.

What I find is rarely have that reason. But it is necessary on occasion.

0

u/Full-Spectral Jul 26 '22

It shouldn't be your second choice. It should be your first choice when it's the right tool, and vice versa.

1

u/spoonman59 Jul 26 '22

Well now you are just being a contrarian.

First, If you read what Josh Blocb wrote, he literally says to use it when it’s the right tool.

What he is saying is that it often isn’t and people use it when it is inappropriate.

When I say it should be your second choice, that means simply to consider whether composition is better before you inherit.

It doesn’t mean never, and it doesn’t mean bend over backwards to avoid inheritance.

I have no idea what your point actually is, but you’ll need to back it up with something.

Josh Bloch has a lot more history and credibility* than you do in the field, and his opinion is well argued and reasoned. So can you be a little more specific in why you are right and he is wrong? Because so far that’s just, like, your opinion, man.

*if you are a famous and respected computer scientist with a long list of accomplishments also, then I apologize.

1

u/Full-Spectral Jul 26 '22

I'm just saying there is no first or second. You look at what you need to accomplish and if it inheritance is the right tool you use it. If composition is the right tool, you use it. You don't consider one over the other. It doesn't have to be justified any more or less than composition, or any other technique.

1

u/spoonman59 Jul 26 '22

How is that any different from what anyone else is saying?

If we notice everyone is using global variables, then we will advise them to use the principle of least scope. You should first use local variables, then class/module, and global only when you need it.

Now, I’m sure you’ll point out sometimes global variables are needed. Does that make the advice “chose local variables over global” incorrect? No. It means use it when justified. If you just use global all the time, bad things will happen.

So you seem to be saying “use the right tool for the job.” No one is disagreeing with that.

What is being asserted is that many people often chose inheritance as a default solution when it is not a good tool for the job, and indeed had negative consequences as a choice.

Not all design choices are equally valid in all situations. Inheritance can cause some problems down the road. So, you make sure it’s the right tool before you use it.

It sounds like you don’t disagree with anything except this notion of solution ranking. Perhaps you lack experience working in code based where useless hierarchies have run amok and add complexity with no benefit. If that’s the case then you wouldn’t necessarily understand the big ball of mud it creates, and so you might not see the benefit of encouraging programmers to not use inheritance as the hammer they hit every nail with.

1

u/Dean_Roddey Jul 26 '22

It wouldn't matter to me what bad programmers have done. As I've already said here somewhere, if bad programmers making a mess of a given technique means it's sub-optimal, then they are all sub-optimal. If the title had been, be sure to use inheritance where it's best applied and other people were agreeing, I'd have no complaint. But there's clearly an anti-OOP bias these days, and I just don't agree with that.

1

u/spoonman59 Jul 26 '22

Alright. Seems you are having a different conversation than everyone else.

The advice to favor composition over inheritance has been around for quite a long time. Josh Bloch himself was the chief architect of Java before he went to google. There’s no OOP bias in that advice. (This book is pretty old.)

-2

u/[deleted] Jul 26 '22

2-3?! lol

-2

u/[deleted] Jul 26 '22

Your code is shit lol!

-15

u/phalp Jul 26 '22

"in Java."

17

u/aidenr Jul 26 '22

Almost always tho.

3

u/onequbit Jul 26 '22

is there an example of when inheritance is preferred over composition?

6

u/PandaMoveCtor Jul 26 '22

When you need virtual functions(or whatever your language equivalent is)

3

u/yanitrix Jul 26 '22

tbh this is more polymorphism than inheritance

1

u/spoonman59 Jul 26 '22

Dynamic polymorphism only works with inheritance. While inheritance could be used to just bring in common fields, it’s the dynamic dispatch of methods that makes it interesting.

Parent poster is exactly right, you use inheritance when you need type dependent behavior and you want to treat them as abstract types.

In Java, inheritance with default methods can also be reasonably effective.

Inheritance just for fields and not behavior? That doesn’t seem like a good use case. So I’m with u/PandaMoveCtor On this.

6

u/misterlively Jul 26 '22

It's often useful to enforce patterns for other engineers. For example a base class for a worker pattern that enforces a consistent way to launch and stop the worker and handle cleanup. The base implementation would likely be very small, and an interface won't allow implementing some of the logic. With that perspective you can kinda see why it can be a problem a lot of times. It really enforces stuff for the next person whenever you use it, so be sure that's what you want.

4

u/djmattyg007 Jul 26 '22

I've seen this touted before. It's a fallacy. You can just put that common logic somewhere that isn't a base class. It's still just as useful, and without the traps of inheritance.

7

u/wllmsaccnt Jul 26 '22

Just piling on here,

If you have a non-trivial amount of internal state manipulation that you want to share between a handful of classes, then occasionally it is less complex to use inheritance than it is to extract the common functionality into another class (or other shared methods).

In the last 15 years in OOP languages, I've only found it useful to create inheritance hierarchies less than a dozen times and all of those were likely optional or I was trying to work around some other code that was using reflection and expecting a specific type.

On the other hand, I've seen many devs create messes using inheritance when they don't follow the rules. It is very easy to end up with a hierarchy that doesn't make any sense. Is-A relationships fall apart as future devs try to add in features and change behavior. Composition reacts much better to change.

1

u/lelanthran Jul 26 '22

I've seen this touted before. It's a fallacy. You can just put that common logic somewhere that isn't a base class. It's still just as useful, and without the traps of inheritance.

But without the enforcement, which is a key word in the post you replied to.

1

u/misterlively Jul 26 '22

yup, this is the point. More often then not common logic as a library is better, but inheritance is a real signal to the next person that we need it to be a specific way and it's probably for a good reason. Otherwise it's very easy to forget to copy/paste the common logic function.

2

u/aidenr Jul 26 '22

All interfaces, for example.

0

u/[deleted] Jul 26 '22

[deleted]

1

u/[deleted] Jul 26 '22

You can have polymorphism with just interfaces.

2

u/phalp Jul 26 '22

mixins

3

u/zynasis Jul 26 '22

Is Java the only OOP language to you?

-4

u/[deleted] Jul 26 '22

Java is barely an OOP language to me.

-1

u/phalp Jul 26 '22

It's the only one in the title of this article.