24 ms·
Why general inheritance is flawed and how to finally fix it
- cpcallen 5y agoI 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. 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.
- SkeuomorphicBee 5y agoOn the "how to program more defensively" point, the author techniques are not meant to protect against malice (you are right that in such case of malice there is nothing that can be done), but instead to protect against foot guns, where innocent and reasonable changes in a module internals might unknowingly break another module. I believe the author's arguments are quite valid, inheritance breaks the concept of a "black box" in Object Oriented Design. Once you inherit from a class, all that class internals become an "unadvertised signature", nothing is a black box that can be transparently changed anymore, any internal change may break a subclass.
- menotyou 5y agoI am always astonished/shocked/surprised how many articles are written trying to solve obscure problems/work arounds resulting from using OOP. How about considering if OOP might be a stupid idea at the first place?
- tabtab 5y agoThe 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. 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? 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. 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.
- CRConrad 5y ago> I've experimented myself with "table oriented programming" Is that you, Bryce?
- stevenalowe 5y agoOr you could learn to use it properly. 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
- alkonaut 5y agoIsn't the "use it properly"-argument pretty much the same arguments as those saying that real C developers don't need the safeties offered by rust, they just need to use C or C++ properly? The whole idea of language design (in my opinion) is to reduce the opportunities for mistakes, without getting in the way (thus reducing productivity). The biggest problem with Java and C# is that they are deceiptively simple. Anyone can get off the ground and the path of least resistance initially is the path of maximum pain in the end. That's the path of making large classes, lots of mutable state, long inheritance chains and so on. The languages aren't forcing anyone to use these antipatterns, but neither are they guiding the hand of the newcomer not to do that.
- p2t2p 5y agoI _hate_ smart asses that do "everything final by default". It all fun and giggles until I can't mock some stupid class in some stupid library that I have no choice but to use just because someone is high on "inheritance is bad" hype. Instead of normal mocking/stubbing I now have to use stuff like PowerMock which does byte code hacking just so I can have a test. How about you stop making decisions for me and let _me_ decide whether I want to inherit your class or not.
- andrekandre 5y ago> I can't mock some stupid class in some stupid library that I have no choice but to use just because someone is high on "inheritance is bad" hype. yea, at the very least, classes public members should be more like interfaces, that way mocking can be done easily in test mode, then in prod build lots of optimizations could "dissolve" the interface and be statically dispatched etc... hmmm....
- al2o3cr 5y agoRe: using composition In the past, it was feared that this would lead to reduced performance but this is simply not the case. Great to see the strong evidence here /s
- burnished 5y agoIt might be more productive if you were to outright disagree with the statement instead of simply noting a claim that isn't strongly substantiated. If you have experiences that demonstrate to you that this claim is weak I'm sure everyone else would be interested in them (I know I would be!).
- vlovich123 5y agoTo add onto that, I tried several different hand rolled alternatives to a c++ vtable and the builtin functionality outperformed them all which was surprising. It’s entirely possible I didn’t know what I was doing but I think my point is that vtables are a language feature that compilers know how to reason about and apply optimizations to. Other concepts not so much.
- tux3 5y agoSomething to keep in mind when microbenchmarking virtual calls is that compilers will happily devirtualize them whenever possible.
- vlovich123 5y agoYeah I’m aware but I made sure the same devirtualization would apply in production too so the compiler doing any devirtualization was good. It was a bit surprising that vtables outperformed std::variant (and I had tried implementing my own hand rolled equivalent of that too).
- pid-1 5y ago"what may be asserted without evidence, may be dismissed without evidence"
- armchairhacker 5y agoI think that composition is absolutely better than inheritance except for one thing: boilerplate. The issue is that boilerplate is kind of important. 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. 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. 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.
- MillenialMan 5y agoI'd like languages to have some kind of "delegate" functionality, where you can just delegate names to point to nested names without screwing around with ownership - it would just act like a symlink. The scope of that action is limited and clear (and easy for your IDE to understand), and it's explicit that the subclass is still the "owner" of that property, which makes the whole thing a lot easier to navigate. E.g. something like: class MyClass: def __init__(self, member_class): self.member_class = member_class # Delegate one member delegate move member_class.position.move # Delegate all members delegate * subclass.position.* Then: a.move == a.member_class.position.move etc.
- nitroll 5y agoIn Python you could do something like: class Base: def func(self): print("In Base.func:", self.name) class Child: def __init__(self, name): self.name = name func = Base.func c = Child("Foo") c.func() #=> In Base.func: Foo
- MillenialMan 5y agoThe reason I'd like the construct is because it's explicit - intent (and the scope/limit of your intent) is encoded in what you create. It's clear you intend to do nothing with that name except symlink to the nested member, so the reader doesn't have to anticipate other behaviour (and can't accidentally do something else with it). Generic assignment doesn't convey the same restricted intent, and it doesn't carry those guard rails. Really though it's a structure that only makes sense in strongly typed languages, so I probably shouldn't have used Python to illustrate the idea.
- nauticacom 5y agoI (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. IMO, the case where inheritance makes the most sense is when you have a set of objects polymorphically answering some question, usually with a simple answer. 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 which is used as such: 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"] You can then pass around a Subset object anywhere (aka dependency injection) and push conditionals up the stack as far as possible. Simply saying "inheritance is bad" gets nobody anywhere.
- BorisTheBrave 5y agoIn most languages Subset would be called a trait or interface, rather than general inheritance. You've picked an example with no fields or overriden methods, so it's impossible for it to demonstrate the shortcomings of inheritance.
- ridiculous_fish 5y agoWhat is the practical difference between inheritance, and a trait or interface with a default implementation? It seems like both risk the addAll() bug.
- rackjack 5y agoMultiple inheritance is basically strictly more powerful than either traits or interfaces with default implementations. I don't think traits or interfaces with default implementations prevent the bug, as I can imagine a Rust implementation that would do something similar.
- magicalhippo 5y ago
- AmericanBlarney 5y agoThe argument is "because it's possible to do misuse with inheritance, you should never use it". By extension then, because it's possible to misuse Java/any programming language/computers/electricity/etc., you should never use it.
- jqpabc123 5y agoSpaghetti code, spaghetti objects. Same stuff in a new way.
- zinxq 5y agoThe term "general inheritance" was not familiar to me as "inheritance across package structures". However, my OOP design intuition feels pretty good about that idea. 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). 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 and correctly consider implications of my code. 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. 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. 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.
- josephg 5y ago> Inheritance is ridiculously useful in the right design structure I’ve made very little use of inheritance since I turned my back on C++/Java a decade and change ago. Can you give some examples where you feel inheritance wins out over composition?
- taeric 5y agoI feel the flaw is in building ontologies. Satic ones, at that. 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. Notably, not compile time. Design. Most failures from mistakes in ontology stall the problem out before release. (Obviously, ymmv.)
- smarks 5y agoThe author is onto something but I’m afraid it’s not explained very well. I think he’s mostly right though. 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! 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. (See also Hyrum’s Law, which is more general than subclassing & inheritance.)
- kaba0 5y agoI have to agree with you. On the other hand, closed hierarchies can be an elegant solution to certain problems. Eg. sealed classes (and basically their single-class counterparts, final classes) avoid the mentioned problems in Java’s parlance. One exception comes to mind though — Java’s SAMs, or in the general case, classes that more or less only wrap around a few methods intended to be overridden/implemented with clear requirements (but maybe this use case also should be restricted to interfaces?) But the default should be to add an explicit open instead of defaulting to non-final.
- nickm12 5y agohttps://lwn.net/Articles/548560/ https://lwn.net/Articles/548560/ 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. 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.
- naasking 5y agoArguably, subtyping in am OO language should either be signatures/interfaces only, or you should go full blown multiple inheritance for everything, as with the Fortress language.
- klibertp 5y agoIs Fortress the same language that required exponential time constraint solving for its type system?
- naasking 5y agoType checking is not exponential last I checked. However, languages with global type inference have exponential behaviour when inferring types for some pathological programs.
- zaphirplane 5y agoGolang ide struggle with answering what implements this interface. The compiler obviously handles that fine It makes it difficult to jump into an unfamiliar project Assuming that’s what you mean by signature/ interfaces
- ncmncm 5y agoInheritance 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. Inheritance is just the right thing once in a while, but Java coders are obliged to apply it well beyond its useful range.
- ivanche 5y agoWhat do you mean by "obliged to apply it"? For example, I very very rarely apply it and nobody is forcing me to create inheritance hierarchy.
- kaba0 5y agoJust because it exists doesn’t mean it has to be used beyond its intended domain. One is entirely free to create flat “hierarchies” in Java. But I agree that in hindsight, final classes as a default would be better. Fortunately nowadays, records and sealed classes remedy this for the most part in java.
- echelon 5y agoFantastic article! 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. 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. Duck typing or traits are better ways to represent polymorphic behaviors. We've known this for over a decade now. Here's hoping that no new languages come with object inheritance as a concept. It's deader than NULL and shouldn't be resurrected.
- mountainriver 5y agoDuck typing is terrible if you want understandable code. The world has largely moved away from this for good reason.
- MaxBarraclough 5y ago> Duck typing or traits are better ways to represent polymorphic behaviors. We've known this for over a decade now. The trend is in the opposite direction. TypeScript enables JavaScript programmers to benefit from static typing, and is seeing widespread use. Python now has type-hints.
- kaba0 5y ago> Duck typing or traits are better ways to represent polymorphic behaviors. We've known this for over a decade now. Any objective measure of that? Because there is a catch, we can’t do what doctors can. There are no double-blind tests for language design. All we have is empirical studies and based on that, OOP languages do objectively much better. So if anything, your exceptional claim require exceptional evidence. But otherwise I agree that these Animal hierarchies are just dumb and many definitely overuse inheritance.
- toolslive 5y agoThere are also problems with the combination of inheritance and concurrency. Google for "inheritance anomaly".
- kaba0 5y agoThank you, interesting read, haven’t heard of it before. Though I feel it would be dishonest to “blame it” on inheritance over on concurrency itself, when we don’t have any good solution to general concurrency as far as I know. We can only deal with it reasonably well by heavily restricting the domain-space to begin with (eg. immutables, no globals/sharing).
- BlackFly 5y agoThe 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. 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? 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]. 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.
- rzzzt 5y agoThe "extends" keyword gives it away that inheritance in Java was not positioned to support the restrictive cases you have in mind (Square : Rectangle, NegativeNumber : Number, TenCharacterString : String). What issues do you see with wrapping? TenCharacterString eg. could use char[] as its backing store and implement CharSequence if you want to get it to speak a common language with String.