I think that composition is absolutely better than inheritance except for one thing: boilerplate. The issue is that boilerplate is kind of important.<p>You don't want to litter your code with "f150.ford.car.vehicle.object.move(50, 50)". You can and should re-implement "move" so that you only have to call "f150.move(50, 50)", but that still requires boilerplate, just in the "F150" class.<p>Often you have class containing all of the functionality of another class, except a bit more functionality. You can always use composition but this happens so often you're creating a lot of boilerplate.<p>You could develop some other "syntax sugar" to replace inheritance. Maybe Haskell's type-classes are better (although they also kind of use inheritance, since there are subclasses). But chances are you'll go back to something like inheritance, because it's very useful very often.
<a href="https://lwn.net/Articles/548560/" rel="nofollow">https://lwn.net/Articles/548560/</a><p>I really enjoyed the article above, which I read many years ago (before Rust 1.0!) which discusses how Golang and Rust handle polymorphism and code-reuse without classic object inheritance. My current thinking is that software objects are a general-purpose tool, but classic object inheritance should rarely be used as it is a solution to a narrow problem—classes should be "final" by default, and if not the inheritance pattern should be completely designed up front.<p>Java had the misfortune to be designed at a time when OOP was the new craze and the design decision to force all code into an object hierarchy has not held up well. I'd rather use languages designed either before or after Java, where you can use objects when they are appropriate and ignore them when they aren't.
I (happily) write a lot of OOP code, "inheritance is bad, use composition" is such a trite and unhelpful dogma that gets in the way of any actual discussion about where inheritance is useful.<p>IMO, the case where inheritance makes the most sense is when you have a set of objects polymorphically answering some question, usually with a <i>simple</i> answer.<p><pre><code> class Subset
class Whole < Subset
def of(items)
items
end
end
class Range < Subset
def initialize(from:, to:)
@from = from
@to = to
end
def of(items)
items[@from:@to]
end
end
end
</code></pre>
which is used as such:<p><pre><code> subset = Subset::Whole.new
puts subset.of(["a", "b", "c"]) # => ["a", "b", "c"]
subset = Subset::Range.new(from: 0, to: 1)
puts subset.of(["a", "b", "c"]) # => ["a"]
</code></pre>
You can then pass around a Subset object anywhere (aka dependency injection) and push conditionals up the stack as far as possible.<p>Simply saying "inheritance is bad" gets nobody anywhere.
The term "general inheritance" was not familiar to me as "inheritance across package structures". However, my OOP design intuition feels pretty good about that idea.<p>This quickly devolves into the inheritance vs. composition argument which isn't where I thought the Author wanted to go (but then sort of ended up going there). I agree with other commenters that it's an overstated idea. Inheritance is ridiculously useful in the right design structure, as is Composition. They both have a place. (Incidentally, bad Inheritance design usually looks very ugly very fast - bad Composition is often less glaring).<p>I find that years of designing in OOP has led me to build designs that have a goal of preventing me from making future mistakes <i>and</i> correctly consider implications of my code.<p>I find that my most immediate designs tend me towards Abstract Classes and Interfaces. While I usually get credit for "programming to the Interface" for this, that's not what usually led me there.<p>I like abstract methods. They (i.e. the compiler will) FORCE me to think about something if I ever decide to create another subclass of the Abstract class. The Author points out the "forget to call super" bug which is particularly nefarious and I avoid it at all costs. I can do that by providing a final concrete method which calls the abstract method. Let the subclasses implement that and never worry about super.<p>Anyway - governing inheritance across package hierarchies seems like a reasonable guideline. As for Inheritance vs. Composition, I don't favor either. When designing a class structure, I just make my best guess (as we'd all do) and find the structure quickly evolves on it's own. Usually, this ends up in a blend of shallow Inheritance trees with logical composition. There's always multiple Class Structures that will work - my goal is to find a reasonable one of those.
Inheritance is flawed, in Java, mainly because it is the only organizing principle offered, so gets shoehorned into all kinds of problems where it is a poor fit.<p>Inheritance is just the right thing once in a while, but Java coders are obliged to apply it well beyond its useful range.
The argument is "because it's possible to do misuse with inheritance, you should never use it".<p>By extension then, because it's possible to misuse Java/any programming language/computers/electricity/etc., you should never use it.
Or you could learn to use it properly.<p>Make no mistake, designing classes to support inheritance is much harder than just declaring everything final, and in many scenarios there is no good reason to do so
The final keyword is one of those places where Java shows its age to me. I agree with the overall point that inheritance is flawed, but I cannot bring myself to conclude that the use of final is the answer to the problem.<p>Simple example, String is final in Java. It is also immutable, and that is (mostly) irrelevant. Lots of string fields on inbound requests have validations, a simple one would be a field that contains a fixed length string. So obviously you validate that at the ingress before passing it down. Now, the question arises, should the core library be defensive and re-validate the string? Why not simply capture the subtype, TenCharacterString and parameterize methods with that?<p>Modern languages get this right. Subtyping is not inheritance. Inheritance is not subtyping. I should be able to subtype at zero cost, I don't need inheritance to do that, [and encapsulation is definitely not subtyping].<p>But Java doesn't have that. You mark something as final and you lose the ability to subtype just to eliminate the possibility of inheritance. On the other hand, to be fair to the argument against final, the real answer to my complaint is a proper type aliasing support.
The author is onto something but I’m afraid it’s not explained very well. I think he’s mostly right though.<p>While reading it I was reminded of a design/implementation style I’ve run across several times over the years which is to find an existing class that does something similar to what you want. Then, subclass it and override methods until you get the behavior you want. And you’re done!<p>This leads directly to the Fragile Base Class problem. I think it also violates the Open/Closed principle. When subclassing occurs across components that are released independently (e.g., a library and an application), it either leads to continual breakage at each release, or ossification of the library. The latter happened to Java’s Swing. It got to the point where it was difficult to fix any bugs, because any “fix” would end up breaking some subclass that relied on the old behavior.<p>(See also Hyrum’s Law, which is more general than subclassing & inheritance.)
I feel the flaw is in building ontologies. Satic ones, at that.<p>There is great value in reducing type errors at runtime. Is hilariously ironic that one of the main tools we reach for seems intent on just moving them to design time.<p>Notably, not compile time. Design. Most failures from mistakes in ontology stall the problem out before release.<p>(Obviously, ymmv.)
The real world rarely sticks with nice hierarchies. Variations of set theory is more powerful, but would generally require merging RDBMS with IDE's, which does deserve more R&D. Using code to manage complex sets is limiting; query languages do it smoother because that's what they were intended for.<p>I've experimented myself with "table oriented programming", but don't have time to explore all the leads I uncover and rework the problem areas. Maybe when I retire?<p>For example, modern CRUD stacks are really just "event handling databases" done poorly. An RDBMS would be better at managing the gazillion event snippets, if it could "talk to" the compiler properly.<p>The "do everything in code" mantra of the web era is a mistake. Databases are better at managing complex relationships and masses of field/UI attributes, code better at non-collection-oriented algorithms. We should use the right tool for the job. "Data annotations" in Java and C# look like JCL's mutant stepdaughter. If that's the pinnacle of CRUD, then slap me silly.
I got the same feeling reading this article that I got from reading _Design Patterns_: that the author(s) present some useful techniques to deal with the shortcomings of Java, but that most of their recommendations seem like kludgy fixes to problems that are absent or at least much less severe in better-designed languages.<p>I also note that, while the author does make some useful points about how to program more defensively, especially in the face of unexpected modifications to super/sub classes written by other programmers, one is inevitably beholden to at least a certain extent on the trustworthiness of code that one depends upon. (Even languages like LambdaMoo that start from the assumption that a program consists of code written by multiple mutually-untrusting programmers cannot entirely protect each against malicious subterfuge by the others.) I therefore question the value of the kind of 'hardening' the author recommends, especially when it might have unfortunate consequences on extensibility and testability.
I am always astonished/shocked/surprised how many articles are written trying to solve obscure problems/work arounds resulting from using OOP.<p>How about considering if OOP might be a stupid idea at the first place?
Re: using composition<p><pre><code> In the past, it was feared that this would lead to reduced
performance but this is simply not the case.
</code></pre>
Great to see the strong evidence here /s
Fantastic article!<p>Object oriented programming gets a horrible wrap on the basis of inheritance alone, and it's no wonder. Outside of limited domains, such as GUI programming, object inheritance makes little sense. Computer science students are right to question their introductory classes on inheritance when they teach contrived examples of dogs barking and cats meowing as an example of Mammal.makeSound() inheritance.<p>It's almost as if we're shoehorning in a code dispatch framework as a major language feature, except that framework sucks and we're stuck building with it. The best strategy working in languages with inheritance is to avoid it.<p>Duck typing or traits are better ways to represent polymorphic behaviors. We've known this for over a decade now.<p>Here's hoping that no new languages come with object inheritance as a concept. It's deader than NULL and shouldn't be resurrected.