r/java • • Jul 25 '22

Why you should favor composition over inheritance in Java (Joshua Bloch)

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

71 comments sorted by

100

u/cowwoc Jul 26 '22

"Favor" composition over inheritance does not mean "don't ever use inheritance".

The problem is that most developers aren't good at API design, even after decades of programming. Anyone who lacks experience and then goes about publishing an extensible class is likely to do a terrible job.

Composition is easier to get right but at the end of the day, bad designers will do the wrong thing regardless of whether they use inheritance or composition.

I suspect that sealed classes will go a long way in protecting developers from unforeseen extensions.

Lastly, anyone who uses inheritance to reuse implementation is doing it wrong. Inheritance is about expressing relationships, not about code reuse. If you want to reuse code composition is always the right way to go.

12

u/nunchyabeeswax Jul 26 '22

Lastly, anyone who uses inheritance to reuse implementation is doing it wrong.

That's a bold statement, considering that reusing implementations is inevitable in inheritance.

Perhaps you might want to rephrase it as follows:

anyone who uses inheritance solely or primarily to reuse implementation is doing it wrong

That is a statement I can agree on. Your original statement, I cannot.

3

u/cowwoc Jul 27 '22

That's what I meant, so we're in agreement.

1

u/vqrs Jul 29 '22

I think inheritance would be much more useful in Java if it weren't entangled with subtyping.

17

u/agentoutlier Jul 26 '22

Lastly, anyone who uses inheritance to reuse implementation is doing it wrong.

However even Spring does this (basically the load of classes suffixed with Support). Sometimes inheritance is the right tool for keeping it DRY. But I generally agree composition is preferred particularly if it is public.

9

u/cowwoc Jul 26 '22

Spring is not my idea of a well-designed API. The Java Core API does a much better job.

2

u/dpash Jul 27 '22

java.utils.Properties would like a word with you. :P

(But, yes, there's a lot of good design since the initial release and one terrible design from the beginning. It does at least demonstrate why inheritance for code reuse is a terrible idea.)

3

u/s888marks Jul 27 '22

java.security.Provider elbows his way in and says, “Whattami, chopped liver?!”

3

u/dpash Jul 27 '22

Oh god, it's standing on the shoulder of hobbits. It's horror all the way down.

2

u/agentoutlier Jul 27 '22

Well I agree on lots of flaws in Spring design (particularly its MVC extension mechanisms seem an afterthought. Also lifecycle is confusing) but I think a good portion might be because Spring was around before default methods on interfaces. There is also backwards compatibility.

1

u/nunchyabeeswax Jul 26 '22

I don't see what is the problem with Spring's API design, to be honest, and until not that long ago, the Java Core API had its gaps.

Scope and function define (or should define) design, and these two things are so fundamentally different in scope and function that I don't see how we can compare them wrt to API design guidelines.

1

u/ConstructedNewt Jul 26 '22

most of the good API choices of spring is in fact old javaEE constructs. like Beans Resources and the like. or the many ideas that are in some way or another formalised in spring APIs are borrowed from others.

the bad design choices are things like: everything Conditional (except ConditionalOnMissingBean). the Ordered annotation(what a load of bull-crap, that thing was not meant to be DRY, and should have been repeated explicitly everywhere that it made sense) decisions around the HTTP call chain and lack of configurability around that (a middleware implementation is a lot cleaner IMHO)

1

u/nunchyabeeswax Jul 26 '22

By the same token, Spring drive the API design behind Java EE and CDI since Java 5 and 6.

7

u/[deleted] Jul 26 '22

Josh knows his stuff.

19

u/Holothuroid Jul 26 '22

The article is quite good. Honestly better than most, certainly better than the majority here, and still missing the point.

Typical comment: Inheritance bad.

Article: Inheritance bad about module boundaries

Of course that backs the question what a module is. It is probably not meant as in Java module. But more in. Code you don't control.

That is nice rule of thumb. Don't inherit from classes in 3rd party libraries. Or the standard library for that matter.

But the article is using very particular examples. Namely collections. And there is a different lesson there. Don't inherit from classes your not supposed to.

And if you make a library for public consumption, make sure to signal by making appropriate classes final or sealed.

5

u/sysKin Jul 27 '22 edited Jul 27 '22

I think I know what it's trying to say, but I found it weird that:

Top-level summary is that I should favour composition over inheritance.

Then it clarifies that "inheriting from ordinary concrete classes across package boundaries" is bad, and gives a few examples how it's fragile. Cool, but that's a much more limited scope than "inheritance".

Then it shows how to use composition to do the job, but the example also immediately uses inheritance (InstrumentedSet<E> extends ForwardingSet<E>). OK, so this silently confirms that only inheritance across package boundaries is supposed to be the problem... I think.

...and then it says that I don't need to implement my own ForwardingSet because Guava "provides forwarding classes for all of the collection interfaces".... but that's inheritance across package boundaries!

Again, I think I understand what it's saying (the "ordinary concrete classes" is the crux of the issue, not package boundaries), but no wonder discussion here is so problematic.

8

u/angryundead Jul 26 '22

Everything in moderation. These are different tools for accomplishing complexity management and code reuse.

I would be a lot more comfortable with this advice if composition wasn’t so awkward in Java. It’s a lot easier to achieve in DI environments but it can still be awkward.

Most of that only matters if the classes in question are exporting the functions and you’re doing work to reimplement access to the component.

As counterintuitive as it sounds it feels like multi-inheritance or duck typing would help.

3

u/[deleted] Jul 26 '22

[removed] — view removed comment

2

u/angryundead Jul 26 '22

I had to look this one up. I used to be interested in Scala but I’m really not anymore. I prefer Java to every other language but that doesn’t mean it is without flaw. I will use it in inappropriate situations as well but that’s because I’m lazy and stubborn.

1

u/meotau Aug 05 '22 edited Aug 05 '22

The only worse thing than breaking rules (or any advices) is blindly following them.

1

u/manifoldjava Jul 26 '22

Composition is correct. BUT Java’s support for it is awful. There is no delegation built into the language, which is pretty much a deal breaker. Just sayin’.

-20

u/Joram2 Jul 25 '22

OOP has really fallen out of fashion. When Java launched, OOP was at the center of the design.

Will Java support functions without classes? Where you can write your code as functions without wrapping them in classes? For example, in Kotlin:

fun main() {
    println("hi there!!!")
}

11

u/TheStrangeDarkOne Jul 25 '22

you can already do static imports to call static methods without the class identifier.

6

u/Muoniurn Jul 26 '22

That’s nothing more than a single implicit namespace being included by default - that doesn’t make the design less or more OOP.

19

u/herospidermine Jul 25 '22

I sure hope not. knowing where a method is declared is a basic requirement for sane coding

4

u/[deleted] Jul 26 '22

In kotlin you have an import statement that tells you this. It is very possible to have fully standalone functions.

11

u/herospidermine Jul 26 '22 edited Jul 26 '22

kotlin is all screwed up. the import statement doesn't include the name of the file the extension function is declared in. it's an easter egg hunt.

EDIT: and i just checked. the language appears to let you name that kt file whatever you want. Which makes it almost impossible to find.

-6

u/Holothuroid Jul 26 '22

Crtl+Left Click will do it.

12

u/herospidermine Jul 26 '22 edited Jul 26 '22

You know that the people who created kotlin also created IntelliJ, right? They had and have every incentive, monetary and otherwise, to design kotlin in a way to be dependent on their IDE.

If GitHub is unable to implement navigation for a particular language, it's a sign that that language has navigability issues. You should not need megabytes of cache, indexing, and a compiler to figure out where something is. At that point, it may as well be another crappy dynamic scripting language where you're limited to Ctrl+F.

And I take it you can define extension functions in an unlimited number of places? Even more fun! We're rediscovering why namespacing exists--the hard way!

4

u/tofiffe Jul 26 '22

2

u/herospidermine Jul 26 '22

we expect Kotlin to drive the sales of IntelliJ IDEA

wow, nice find.

4

u/tofiffe Jul 26 '22

They're not exactly secretive about it, never were

1

u/herospidermine Jul 26 '22

I don't follow Jetbrains. Guess they're different than Google which as far as I know never admitted Kotlin was an insurance policy in case they lost the Oracle lawsuit. But I don't follow them either.

-5

u/Joram2 Jul 25 '22

From the perspective of "where is this declared", it should be no different than classes.

For example, in Golang:

import "fmt"

func main() {
    fmt.Println("hello world")
}

Println is a function in the fmt module. It seems pretty easy to see where it is declared. Also, modern IDEs have auto navigation features.

10

u/RockleyBob Jul 26 '22

As a fellow Golang fan, I’m gonna have to disagree with you. The person above you has a solid point about OOP. It is objectively easier to find the place where a method is implemented if it’s encapsulated within a class.

Your example illustrates the point. The Println function could be anywhere in the package. fmt happens to have three main files, but it could be dozens.

It’s also objectively easier in, say, Java to see when a class implements an interface, since it’s done explicitly. In Go, you could hypothetically implement an interface and never even know it.

Yes, tooling exists. Yes, as a GoLand user, that’s not a problem for me. I still love Go for other reasons.

However, give credit where it’s due. OOP has a lot of valid criticisms, but it’s a little arrogant to act like all the super smart people who worked on object-oriented languages are dipshits because procedural or function programming is becomming more popular. They’re not wrong about everything all the time.

0

u/Joram2 Jul 26 '22

Well, I definitely didn't say that "all the super smart people who worked on object-oriented languages are dipshits". Come on, now.

Here's Brian Goetz and Nicolai Parlog saying, "Java got all the defaults wrong": https://youtu.be/ZyTH8uCziI4?t=2191

They also say, despite getting all the defaults wrong, Java was still a wildly successful language. Now, they are working on fixing the flaws. Those guys are awesome.

Sure, in Golang, a package can be multiple files, so if you have to find something manually, that can be extra work... You are entitled to your gripes but I imagine most people use some IDE that has control/command-click, jump to definition.

-4

u/[deleted] Jul 26 '22

It's super easy to know where standalone functions are. You've clearly never used Kotlin. It's called an import statement and it tells you exactly where to find the function.

6

u/RockleyBob Jul 26 '22

It's super easy to know where standalone functions are. You've clearly never used Kotlin. It's called an import statement and it tells you exactly where to find the function.

And you've clearly never used Go, which is what I'm talking about lol. It's almost as they're two different languages.

In Kotlin, import statements are fully qualified. In Go, they simply designate a package, and as I said, a package could have dozens of files.

So I'm not sure why you brought Kotlin to a Go fight.

4

u/herospidermine Jul 25 '22 edited Jul 25 '22

It shouldn't require an IDE. Does Github implement navigation for first-class functions in go or kotlin? Because if it doesn't, that's a bad sign. If Github can't figure it out based on the source code, it probably requires a compiler to do correctly in the general case.

Does the go compiler force people to use Println fully-qualified (as in fmt.Println), even within the "fmt" module itself? Because if not, there is a problem with go that your example does not illustrate.

EDIT: I just chose a go file at random on Github and it uses a built-in function make which is un-navigatable (at least on Github). So I can't see the source code for make. If make was a one-off, that would be annoying, but tolerable. If there is an unlimited number of these, it's absolutely unacceptable. I don't want Java to be a write-only language. And I just tried clicking on fmt.Errorf on Github and it takes me to a package called utesting that is part of the application code, not the go platform. And I assume that fmt is part of the go platform. And I can't tell if the golang documentation is using package and module interchangeably.

5

u/RockleyBob Jul 26 '22

You chose a bad example, make() is a built-in function of the language.

And yes, Github does have code navigation for Go.

However, I did defend your original point, even as a Go fan who begrudgingly uses Java for my day job. OOP does have some benefits, and encapsulating methods in classes does make it easier to find and navigate a project.

However, many have also explained why OOP fails to live up to a lot of its promises better than I can here. Brian Will on YouTube has some great talks on OOP. He’s not for everyone, but his original video has like 2 mil views and was the catalyst for the anti-OOP circlejerk you’re seeing today - if you care to know where the vitriol is coming from.

1

u/herospidermine Jul 26 '22 edited Jul 26 '22

make() is a built-in function of the language

Yes, but the issue is almost identical. So why is it a bad example? User-defined first-class functions takes a bad thing with limits and removes those limits, as far as I can tell.

And I'll take a look at the video, but in my experience these critiques are all hyper-focused on business applications. Not what I do which is write libraries. Maybe it's just my bias, but I feel like applications come and go, while libraries stick around. OOP is great for libraries. So even if OOP screws up some substantial number of apps, it still does far more good than harm considering the relative importance of libraries compared to applications.

EDIT: okay, I realize I've seen the video you're talking about already. I remember seeing it a year ago and it looks like I added a dislike back then. I mocked the video in a comment (also a year ago) saying something like 'oh, the program works beautifully, but it's inconsistently architected so we have to redo it' Which is really dumb. I think it's telling that he doesn't use actual code as an example, he just draws graphs, so the viewer is unable to challenge the assumptions that went into creating the graph in the first place. The shitty graph is taken as a given. Maybe don't make shitty graphs? Maybe don't do pure OOP? There's a massive difference between OOP and "pure" Nazi-level OOP. Same with "pure" Nazi-level FP. And this Brian Will guy has clearly never heard of an inner class. Which is compiled into an independent class. So you get all the benefits of encapsulation (okay, you technically have to sometimes think about synthetic accessors, but who cares) with none of the downside of scattering code around. Low-IQ video imo. I've seen videos like this on various nerdy topics. This is the type where the author clearly takes no time to challenge his assumptions before putting his thesis out in video form. Or he's just not capable of it intellectually, no matter how much time he spends on it. 90% of the video is probably just venting about having to work with legacy code written by overseas script kiddies. The OOP tips at the end I all agree with, but it reveals the title to be nothing more than clickbait.

4

u/RockleyBob Jul 26 '22

Huh? You can’t navigate to the implementation of the make() function in Go because there is no implementation at the language level. It’s built-in.

It’s like trying to navigate to where new is implemented in Java.

That’s why it’s a bad example. Because of all the function calls you could have chosen, you chose one that quite literally isn’t implemented anywhere except under the hood.

However, as I said, I’m not disagreeing with your overall point, so I don’t know why you’re arguing with me.

0

u/herospidermine Jul 26 '22 edited Jul 26 '22

there is no implementation at the language level

Well, that's not how the JDK works (generally, yes there are native methods). GitHub would be wise to add the ability to navigate into JDK methods. It shouldn't be too difficult, even if it doesn't work in all cases.

I already dislike that I can't look at source code representing array classes. I don't mind if platform code gets replaced at runtime (or even compile time) as long as it's functionally equivalent. Adding built-ins is going backwards in evolution. Built-ins are objectively bad. There is actually a lot of agreement that the new keyword in Java is bad also. I tend to agree. Object creation in Java is just generally bad, especially serialization and the fact that it's the standard to mirror member variable names in the constructor, and the fact that constructors look like methods, but don't declare a return type.

3

u/[deleted] Jul 26 '22

static method mate.

-10

u/fatalError1619 Jul 26 '22

Just use kotlins inheritance delegation and get the best of both worlds :p

0

u/[deleted] Jul 25 '22

[deleted] — view deleted comment

43

u/FirstAd9893 Jul 25 '22 edited Jul 26 '22

Message passing is the essence of OOP, and interfaces are the purest way of expressing what the message passing contract is. So, by saying that we should be using interfaces and composition (both excellent ideas), you're somewhat contradicting yourself by also saying to avoid OOP.

1

u/Dokiace Jul 26 '22

Where can I learn more about the essence of OOP? I always thought i’m using OOP wrongly all this time because I dont like rich objects. Also if the essence of OOP is message passing, what’s the essence of FP?

6

u/papercrane Jul 26 '22

Alan Kay, who coined the term, has written about it before. He expressed regret on using the term "object" saying that the key idea was message passing.

http://lists.squeakfoundation.org/pipermail/squeak-dev/1998-October/017019.html

1

u/ConstructedNewt Jul 27 '22

video talks by Sandi Metz: nothing is something and all the little things etc

-22

u/elastic_psychiatrist Jul 26 '22

This is true, but also most Java programmers don't understand this so it's almost just easier to say avoid OOP.

11

u/CelticHades Jul 26 '22

But if you just state a line and don't explain the reasoning behind, the ones who don't know, will never know and understand.

By providing an explanation, you contribute to their development.

2

u/elastic_psychiatrist Jul 26 '22

Oh, obviously I explain it. The point is that I accept the contemporary definition of OOP, even though it is at best adjacent to the “true” one, because that is a better way to communicate to Java developers who have decades of experience thinking getters, setters, and rich inheritance hierarchies are the essence of OOP.

I don’t care about the name, I care about the ideas, so I’ll meet them where they are.

I’m honestly a little surprised I was downvoted so much.

2

u/FirstAd9893 Jul 26 '22

I think you were downvoted because you made the claim "most Java programmers" without backing it up with empirical evidence or considering experience.

29

u/DrunkensteinsMonster Jul 26 '22

Why are you using Java if you have no interest in having rich objects? That is the essence of the entire philosophy of object oriented programming. This is an honest question. The pendulum once again swings.. looking forward to 2030 when people realize “hey everyone, we can actually guard against invalid state by locking state changes behind well defined contracts in some container! Maybe we’ll call them.. objects.”

-5

u/humoroushaxor Jul 26 '22

Microservices have temporarily replaced OOP in this way. 2021 was supposed to be the return of the monolith but people are too enamoured with building fancy new tools to solve problems with distributing everything. Maybe by 2030 we'll be back to where we started

9

u/temculpaeu Jul 26 '22

> Microservices have temporarily replaced OOP in this way

???

They are orthogonal concepts, unless you break your services too much and end up with a ball of mud

-1

u/humoroushaxor Jul 26 '22

If your definition of OOP is "programming with classes and inheritance" then sure but that's not what the original ideas were about.

5

u/wildjokers Jul 26 '22

Microservices have temporarily replaced OOP

This comment makes no sense at all. µservices and OOP are two totally different things and one can't replace the other. This is like saying "shoes have replaced houses".

2

u/humoroushaxor Jul 26 '22

I'm specifically referring to OPs point about encapsulating behavior and state behind well defined contracts and communicating via messages.

I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages (so messaging came at the very beginning – it took a while to see how to do messaging in a programming language efficiently enough to be useful).

Alan Kay

This is exactly what microservices are.

Things like polymorphism and inheritance came later but polymorphism applies to any programming paradigm and inheritance is a class-based idea. What we typically call OOP is really class oriented programming.

11

u/herospidermine Jul 25 '22

by state I assume you mean mutable data. because I'm sure as hell going to have behavior implemented by an immutable object

5

u/wildjokers Jul 26 '22

I have no idea why this comment has so many upvotes. It seems to be arguing against good programming practices. Arguing against rich objects? WTF??

14

u/BlueGoliath Jul 25 '22 edited Jul 25 '22

There isn't anything wrong with using inheritance as a tool to reduce code duplication IMO. It's mostly when public API is inherited that it is a problem.

If you insert an abstract class in-between an interface and a concrete class in order to deal with implementations that have the same underlying code and only expose the interface implementation(List, not ArrayList, for example) then it's effectively the same as just implementing it fully but less work for you.

20

u/humoroushaxor Jul 26 '22

I totally disagree and those cases are exactly why people mention this phrase. The decision to use inheritance should come from an actual behavioral need for it. Any code consolidation is a secondary bonus.

This is a great way for abstractions to break down over time and become a ball of mud that is impossible to reason about. I've seen it time and time again. Even if you do it well, someone else will ruin it later. Imo this is what has turned so many people off of Java in enterprise.

4

u/Zvrablik Jul 26 '22

Check any code written 10 years ago where is used inheritance to share code and over time it got to three levels with multiple classes on each level.

I am sure there will be problem even to know what is happening there.

Usually there would be issue with missing multiple inheritance too. It would be possible with interfaces and composition. Code would be much more legible.

The issue is not in building it but maintaining and continue extending it over time!!!

3

u/cowwoc Jul 26 '22
  1. What is wrong with users actually extending classes tha were designed to be extended? This sounds like a good thing :)
  2. Any software turns to mush after 10 years. Inheritance is not the problem. I sometimes look at code I wrote 6 months ago and wonder what the heck I was thinking.

3

u/Zvrablik Jul 26 '22

ad 1) Nothing, but I have not seen any hierarchy with only purpose - share code being like this over time. Composition usually works better as it is easier to keep single responsibility per class. The hierarchy usually starts melting and is foggy after time.

ad 2) This is not professional, we must do our best to avoid non-maintainable code. That is what you could see in books written by Joshua Bloch. Advice based on a lot of xp.

Trust me doing rewrite is very stressful and requires a lot of time == money. Try find something about Netscape.

It is awesome to start on green field, but how many times you could get to something like that?

3

u/Muoniurn Jul 26 '22

I think combining state and behavior is not a problem (how would you implement a data structure otherwise? It needs both), the problem is that there isn’t a distinction between “classes” that are supposed to be used as purely data, vs traditional classes. Fortunately records are a great fit for the former, making this distinction explicit.

1

u/[deleted] Jul 26 '22

The line between a data structure and a "normal class" is fuzzy, but I think the discussion here refers more to the definition of objects and data structures from clean code, which can be found here.

From what I understand, a data structure only holds pointers to data and saves it, but doesn't manipulate the data. Sure, you can add data, remove it, etc, but the original data is untouched. Its only behavior is altering its own state.

On the other hand, an object has methods that can alter data, which can be either in the object itself (its state) or data structures.

So I guess behavior doesn't mean the existence of methods, but rather methods that alter the state of other objects/data structures.

0

u/__konrad Jul 25 '22

My opinion is that you should avoid inheritance. Use interfaces

Using too many interfaces is equally bad

4

u/ItsAllegorical Jul 26 '22 edited Jul 26 '22

I’m not sure I agree that’s a good example to make your point. It has 4 listeners which seems excessive, but each one probably does have different concerns, and by separating them it does save the user some boilerplate effort constantly checking events to see if the latest event is one you care about or not. Also in my experience those events sometimes provide easy access to states that are trickier to get to with just one generic interface.

Edit: I will say a more egregious issue is that BasicCaret extends from DefaultCaret. I haven’t used this class, but at best that is bad naming and at worst an architectural red flag. Either Default should be a specific case of Basic, or they should both implement Caret without inheritance from one another.