273 points · by chmaynard · 7y ago · 184 comments
Ever since then I've been on an anti-inheritance kick, although for the last several years it's polymorphed into an anti-OO kick.
Anyway, I suspect most readers here have heard the idea that inheritance should be used in limited circumstances (or not at all), but I wonder what proportion of college students get that message today.
Imagine you have an interface with 20+ methods, such as the List interface. And you want to create a new implementation of this interface, which is almost identical to an existing implementation, except for one tiny difference. Example, you want an CustomArrayList implementation that doesn't allow the number 666 to be populated into the list.
With inheritance, you can accomplish this in just a few lines of code. Extend the existing implementation, and override just the methods that need to be overridden.
Whereas with composition, you now need to manually implement all 20+ methods in the interface, just to make the pass-through call. This adds a tremendous amount of boilerplate to the code.
Depending on how many methods are in the interface and how invasive the changes are, this boilerplate is sometimes worth it and sometimes not worth it. Ideally, languages will add built-in support to facilitate this pattern without the associated verbosity. But until then, people will continue to use inheritance just because of how much less verbose it is.
Inheritance is not necessary for this. The traditional way of achieving this in functional languages is to use a closure to return an object/record. Instead of brittle inheritance, just pass this object to another function that returns an object modified however you want it. Objects can be combined too, achieving the same goal as multiple inheritance, but less dangerous. Simple, easy, succinct, composable.
Well, you can somehow achieve a part of it in Python with implementing magic __getattribute__ method:
class CustomArrayList (object):
def __init__(self):
self.list = ArrayList()
def add(self, item):
if item == 666:
raise
self.list.add(item)
def __getattribute__(self, key):
"""For rest of the methods use them as they are.
"""
try:
attr = object.__getattribute__(self, key)
except AttributeError:
attr = object.__getattribute__(self.list, key)
return attr
However, most probably no one will like you if you use this method :)I have used inheritance in a way to make accessing code more seamless and easier for development. But without inheritance, I end up with a lot of boilerplate code, imports, etc...
Doesn't duplication go against the DRY principle? I know you are saying "wrong inheritance", but some people are saying all inheritance is wrong...
I believe this would work for you.
IMHO inheritance and especially deep inheritance hierarchies are almost always the wrong thing to do. I know of few exceptions and have ended up regretting breaking that rule on the few occasions I allowed that to happen. These days I just don't use it at all on principle. I'm very weary of using frameworks that depend on or over use inheritance. E.g. much of Spring looks problematic and convoluted to me. I use it but I tend to avoid the stuff that is too hard to understand. Five or more layers of classes is just insanely misguided IMHO.
Most of those layers are just working around the previous (wrong) decision to use inheritance. It's like the broken windows theory. Inheritance leads to more inheritance. It causes all sorts of problems down the line and you can't change it once you have users extending your classes.
I love that modern languages disable this. E.g. Kotlin has closed classes by default (the opposite of Java) and does not allow inheritance between data classes at all. This is great and communicates clearly that you should not be littering your code base with 'open'. This encourages good design that does not depend on scattering functionality all over the inheritance hierarchy or the endless levels of indirection. They even provide a compiler plugin to deal with spring that re-opens classes at compile team so that Spring and other legacy Java framworks can do it's dirty business of reflectively extending classes without requiring the code to be compromised.
I find it ironic that e.g. the Javascript community has worked hard to get classes and inheritance and are essentially repeating all the same mistakes people were making with Java 20 years ago by overusing inheritance. Most of 'modern' javascript to me looks like a blast from the past.
IME JS classes are less about inheritance (which remains compositional anyway, though classes do make these easier what with not having to maintain the prototype chain or hand-roll super calls) and more about the various syntactical convenience of class declarations, namely that you don't have to deal with the Function / Function.prototype crap, the hand-rolling of `new` mandates (a class ctor is always called through new), the requirement of explicit strict mode (class declarations are always strict), method shorthands (they do exist on object literals, they don't exist when adding to a prototype property by property), …
const createCounter = ({ startAt = 0, incremementBy = 1 }) => {
let count = startAt
return {
currentCount: () => count,
step: () => {
count += incremementBy
}
}
}
const counter = createCounter({ startAt: 5 })
counter.step()
versus class Counter {
constructor({ startAt = 0, incrementBy = 1 }) {
this.startAt = startAt
this.incrementBy = incrementBy
this.count = 0
}
step() {
this.count += this.incrementBy
}
}
const counter = new Counter({ startAt: 5 })I think the last time I personally abused inheritance was when using Backbone.js more than 5 years ago, and that experience was what finally tipped me over the edge to start learning more about functional programming.
You can go much farther and discover that OO state mutations across multiple methods can be replaced with higher order functions that let you keep state mutations local, within context of each function. Suddenly OO becomes this weird very unproductive and error prone way of writing and reading code. An entire OO concept is just bad, always was, nothing can fix it.
At least with Javascript higher order programming was always possible.
I highly encourage anyone with doubts about OOP to actually complete that Kata.
In short, inheritance should be confined to removing conditionals in problems with shallow-wide [1] inheritance graphs, where things truly "is-a" thing, not "have-a" thing [2]
Real life examples I've encountered: * buttons in a toolbar implementing a command interface * database drivers extending a base implementation * web-server endpoints extending a base implementation
Some of the most complex software in the world is currently modeled using OOP. If one is ever in doubt, look into creating plugins for IntelliJ. The whole program is a massive exercise in OOP modelling, and it works pretty well (if not a little slow some times) [3]
[0] https://www.youtube.com/watch?v=8bZh5LMaSmE [1] http://cek.io/blog/2014/05/26/poodr-ch-7/ [2] https://stackoverflow.com/questions/2218937/has-a-is-a-termi... [3] https://www.jetbrains.org/intellij/sdk/docs/basics/getting_s...
I'd go with 2:-
- messages
- objects that have conversations with other objects through messages to achieve a cohesive purpose
inheritence is essentially a method of sharing code without going through a message, so not really OO, you can use any sharing mechanisim you like to make cohesive objects.
moreover, plenty of FPs (I'm looking at you erlang) use message passing all over the place, as, arguably the most important feature of the language, with things that vaguely look like objects (gen_servers) but I would not really call erlang an OO language, except maybe to joke to an OO programmer that an FP is truer to the original intent.
actually, Alan Kay said Erlang was most like his concept of OO.
Ruby has some nice hooks for when an object doesn't have a method, at which point you can dynamically resolve it. Much advice in the OO world and its principles are really just to do with message routing, and a lot of Design Patterns are about how to do it when the type system fights you
but even if you are stuck with your C++/Java/C# type languages, then I think it is still useful. I've often seen in the first 10-15 minutes with "traditional" advice that set off down a path of design that ultimately causes a lot of struggle between OO and the typing system, most often because of naming things too early warping the mental rather than recognizing traits of interactions.
Erlang makes messages an even more central element, as the whole language is built around the concept of inboxes and asynchronous message passing (synchronous message passing being a special case).
Better type systems are in vogue now, for really good reasons. But I wish we don't ignore lots of good ideas from dynamic languages like Erlang or Mozart/Oz. Every time I open CTM or SICP I find great insights I had already forgotten.
(I pity the educator if he or she didn't know this.)
Polymorphism, no; I mean, how can we substitute different kinds of objects into the same situations dynamically without polymorphism. OOP is almost synonymous with polymorphism.
But we do not have to bundle code and data representation together; there are other approaches to OOP, like generic functions.
Rather than having one big memory chunk, and one big function chunk (like the old DATA DIVISION and PROCEDURE DIVISION of cobol), you divide thoses into smaller data+procedure bits that idealy map to existing concepts from your domain.
That seems like a much more effective way of seeing the thing. Although once you start adding parallelism and asynchronous communication, you do probably end-up in something closer to the Kay definition.
AFAIK in C++ you must use inheritance if you want polymorphism since there is no real concept of interfaces.
If you want to do things the Java or C# way, then you're correct. You'd want a pure virtual interface, which mimics what you'd get with Java or C#.
For example, you might have a bunch of things, some of which: (a) can be rendered in some display - could be console, HTML, print output, screen, don't care; (b) can be serialized to a variety of media; (c) have some common configuration, that interacts with some configuration management system; etc.
If you try and shoe-horn these commonalities into a hierarchy, you end up with classes that advertise being able to do too much and need to have "not implemented" error conditions, breaking the Liskov substitution principle.
Interfaces are a way of breaking out. They're additive, rather than hierarchical, from the implementing class perspective.
The other big problem (a bigger problem IMO) with inheritance is coupling. I don't think there's any closer coupling between two pieces of code in an OOP system than inheritance. Changes in a base class can radically alter behaviour in all descendants. Depending on the implementation of overriding, descendant behaviour can be accidentally hijacked with no compile time or run time warning merely by updating a dependency. The API by which base class and descendant class interact is bidirectional, with the flavours of both library (you call them) and framework (we'll call you), and intermediate internal state when e.g. overridden protected methods are being called is usually sorely undocumented and liable to change.
Java (and .Net by copying) choose to make interfaces additive and superclasses combinatorial. It's a design decision and in no way intrinsic. Other languages have different choices.
Try Go if you’d like a familiar language without the inheritance that you can pick up in an afternoon.
Python manages quite well without encapsulation.
But the linked article is reasonable. Less reasonable articles like this one exist, however: https://codeburst.io/inheritance-is-evil-stop-using-it-6c4f1...
These are the articles where someone saw that the "cool kids" don't like/use inheritance, and so adopted the position to try and be "cool".
Don't try to be cool, try to understand. Inheritance doesn't say, "Create a complex inheritance tree of interdependent classes". That's the strawman. Remember that.
None of these is a fundamental tenet. See the article linked here [1]. The fundamental tenets are the five "SOLID" [2] principles.
Object-oriented design is not well-taught in general. The impression most people normally have of it is quite different from what it actually is.
P.S. You may also find [3] interesting.
[1] https://news.ycombinator.com/item?id=18250255
Single responsibility principle - something we can all agree on but doesn't help you decide between two non hideous designs
Open/Closed Principle - the original advice was so terrible that we ignore it and pretend it means something else that has very little to do with open/closed
Liskov - technically true but very few applications are bad or incorrect because of this violation(especially with the recent move away from inheritance)
Interface Segregation - Sure it's useful to split up interfaces sometimes.
Dependency Injection - Sometimes useful for testing or IOC.
Single Responsibility is achieved by composition
Open/Closed is probably the one that fits least with FP, but it seems like FP achieves the same result by replacing both extension and modification with composition.
Liskov Substitution can be replaced by a subtyping or duck typing.
Interface Segregation seems like its more about design than programming. However, to the degree that it applies to programming, composition seems like it actually better meets this principle than inheritance.
In terms of Dependency Inversion: If anything, it seems like one of the biggest problems with FP is that it makes it easy to take this principle too far by making things too abstract (e.g. the category theory aspects of languages like Haskel seem like they could easily be abused).
I'm not super experienced with OO so am I maybe misinterpreting these principles?
So that is to say, if you want to dynamically substitute objects of class D1 and D2 in the same places in the program, these classes have to inherit some base B. Then D1 and D2 objects can work in places that require a B. For this reason, sometimes the B is a dummy that contains no implementation at all. In recognition of such dummy bases, some languages have "interfaces" and "interface inheritance" to formalize the concept.
In true OOP, there is no such requirement for D1 and D2 to be a new kind of B. Objects are substitutable into a situation if they simply respond to all the required methods. Inheritance is then used optionally just as a trick for implementation reuse. That is to say, we not only want D1 and D2 to be substitutable, but since they are similar, we would like to have a large fraction of their code in common, not to mention the instance data which that code refers to.
The problem is that inheritance is like a software fork. There is this basic implementation of something B, and then these derivations D1 and D2 are like branches: they use the B code, but they replace some of it with their own versions of functions. Those functions initially correctly mimic what their counterparts in B are doing. But if B is subsequently maintained, that can fall apart. B functions can be altered, while their counterparts in D1 and D2 remain the same, not incorporating the new logic. This kind of inheritance situation works best when it's all maintained by one developer, or team, as a cohesive whole. Or else, the base has to be very well designed for inheritance and maintained very carefully.
Inheritance has issues that interact with mutability. The circle-ellipse problem goes away if objects are immutable. In the Common Lisp object system there is an analogy there in that numbers of type rational are subclassed by inheritance into ratio and integer. An integer isn't a new kind of rational; it's a restricted kidn of one, just like a circle is a restricted ellipse. Since we cannot mutate an integer (it is what it is), inheritance models things just fine here; it is quite suitable for partitioning a mathematical set. In terms of substitutability, it is perefect: certainly wherever rationals are allowed, we should be able to use an integer or a ratio, just like where ellipses are allowed, we should be able to use a circle. If we ask an integer what its denominator is, we get 1.
That word "true" is doing a lot of work for you here. There are other definitions of what true OOP is, at least one of which (SOLID) appears in the comments on this article. By calling yours "true", you avoid having to do anything to defend your choice of definition. But if someone does not already buy your definition, calling yours the "true" one is completely unpersuasive.
> There is this basic implementation of something B, and then these derivations D1 and D2 are like branches: they use the B code, but they replace some of it with their own versions of functions. Those functions initially correctly mimic what their counterparts in B are doing. But if B is subsequently maintained, that can fall apart. B functions can be altered, while their counterparts in D1 and D2 remain the same, not incorporating the new logic.
True. But there is no software technique that is proof against bad maintenance. So your argument here is that this technique faces the same problem as every other technique. That's not much of an argument.
The tradeoff is that if D1 and D2 are similar, we wastefully duplicate code, and have future problems like fixing a bug in one, but not the other, and deal with nearly identical but subtly diverging versions of almost-the-same thing.
This is the TXR Lisp interactive listener of TXR 215.
Quit with :quit or Ctrl-D on empty line. Ctrl-X ? for cheatsheet.
1> (defstruct fixed-list nil
a b c
(:method car (me) me.a)
(:method cdr (me) (list me.b me.c)))
#<struct-type fixed-list>
2> (new fixed-list a 1 b 2 c 3)
#S(fixed-list a 1 b 2 c 3)
3> (car *2)
1
4> (cdr *2)
(2 3)
5> [mapcar square *2]
(1 4 9)
6> (cons 0 *2)
(0 . #S(fixed-list a 1 b 2 c 3))
7> [mapcar square (cons 0 *2)]
(0 1 4 9)
:)I am trying to think of a commonly used language that exclusively uses inheritance to implement polymorphism. (Unless you consider Java’s interfaces to be inheritance when they are the language’s alternative to using inheritance.)
Having come to Java from C++, I always considered Java's interfaces to be a syntactic sugar on top of inheritance. In C++, there is (or was, back then) no meaningful difference between "interface" inheritance and "class inheritance" - and why would there be, if it boils down to stringing up vtables together?
I think this is the main disadvantage, at least in languages like C++ and Java; if you want to be dogmatic about the OOP-ism of encapsulation and that stuff, all those "methods that just call another method on the composed sub-object" create lots of bloat that a compiler may or may not be smart enough to inline, but a human certainly would have to deal with --- and that adds overhead when debugging and otherwise maintaining the code. Speaking as someone who really hates such "useless" code, composition (especially sometimes of the nested variety) can get annoying really really quickly ---needing to "thread the call" to the right place through many composed objects just feels more like busywork than accomplishing anything functionally useful. If you inherit, you automatically get the union of the methods (and only when there's name collisions do you need to disambiguate), but inherit too deeply or widely and it gets more difficult to find where the code is.
Of course, none of this is relevant at all to the code I normally write using C, where there is no inheritance and everything is composition, and not being an "OOP purist", I'm perfectly happy with BAR_dosomething(&foo.bar);
Doing this is a pretty strong code smell. If you have chains of object references that need to know about the internal structure of other objects, perhaps think about the Law of Demeter? https://en.m.wikipedia.org/wiki/Law_of_Demeter
Although the LoD increases the adaptiveness of a software system, it may result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead
Suppose foo() inside class X needs an extra parameter or similar, but that parameter actually needs to come from A which contains an instance of B which contains a C which contains a ... ... which contains the X. Instead of changing only foo() and the b.c....foo() in A, being dogmatic means having to change all the do-nothing wrapper methods on that call chain.
If anything, I'd say wrappers are the real code smell. You can probably tell I'm not a fan of OO; I've encountered the aforementioned situation countless times, where the real purposeful change takes a tiny fraction of the time compared to going through all that other do-nothing code and changing it too. The mind-numbing depth of indirection and wasteful bureaucracy is excruciating.
I am really interested in improving my coding using functional programming, composition, etc... but so far, I haven't been able to understand the benefits in my current circumstances. (I've done a lot of reading already) I am hoping I will run into one, so I can see clearly why it's worth the effort to implement. (ie, implement something new when upgrading/replacing some old OOP code...)
This is such a common pattern that adding syntactic sugar for it may be a good idea. Maybe something like
from x expose y, z, w from x expose y->z->w
otherwise you just wrote an alternative syntax for a wrapper, which then - in accordance with Law of Demeter - you'd have to repeat in y and z.Here's the crucial part: in Eiffel, methods can have preconditions and postconditions, and overridden methods in subclasses must honour those conditions in specific ways:
> The principle of subcontracting follows from these observations: a redefined version of r may keep or weaken the precondition; it may keep or strengthen the postcondition. Strengthening the precondition, or weakening the postcondition, would be a case of “dishonest subcontracting” and could lead to disaster. The Eiffel language rules for assertion redefinition support the principle of subcontracting.
In a sense, languages which support inheritance might not actually be doing it correctly if they don't support these rules of 'subcontracting'.
Why should we write a ton of boilerplate just to forward a message to a contained object? Why can't we just have:
type MyType {
member containedObject SomeOtherType
forwardTo(containedObject) MethodA, MethodB as SomeOtherName, MethodC
method SomeNewMethod() {some implementation}
}
Then the compiler can optimize the path to call the delegated object directly rather than through a secondary call via this object, since it knows what our intent is. class A {
def foo(): String = ...
def bar(): String = ...
def baz(): String = ...
}
class B {
private val a: A = new A()
def foo(): String = ...
// Export a's methods as b's, except for foo, and rename baz as qux
export a.{foo => _, baz => qux, _}
}
val b = new B()
b.foo() // b's implementation
b.bar() // a's
b.qux() // a's bazRust is talking about adding it as well[1].
I guess Haskell does too[2].
[0]: https://kotlinlang.org/docs/reference/delegation.html
[1]: https://github.com/rust-lang/rfcs/pull/2393
[2]: https://downloads.haskell.org/~ghc/5.04/docs/html/users_guid...
class MyType {
has SomeOtherType $.containedObject handles ('MethodA', MethodB => 'SomeOtherName', 'MethodC');
}
Very useful when you need it. package MyClass;
use Moo;
has member => (
is => ‘rw’,
handles => [qw[
methodA
methodB
]]
);[1] http://docs.groovy-lang.org/2.4.9/html/gapi/groovy/lang/Dele...
The composition pattern is just one of the many ways Java programmers figured out to write more code that does essentially nothing.
That's why Java programmers will be in demand forever, whereas more productive programmers will optimize themselves out of a job.
My other complaint is when the base class is updated independently of the child class. Suddenly your code is breaking because a new field is being set in the original function but not your override. For that reason I tend to inherit to extend only, as much as possible. I prefer to write a wrapper if it's a neater solution.
I tend to agree. We need something closer to set theory to manage variations-on-a-theme rather than hierarchies: a buffet where one can pick and choose the parts as needed, and referencing groups of parts using group names to save time and provide abstraction/factoring. It's why I mentioned we need to get some inspiration from relational, which is heavily influenced by set theory.
I have found this site incredibly good for Django's class based views (which I struggles to understand before using it). https://ccbv.co.uk/
I wish there was a way to auto generate something like this for all inherited code.
https://tenderlovemaking.com/2014/06/02/yagni-methods-are-ki...
Is it just me, or does anyone else feel like this tenderlove/tenderlovemaking thing is a bit uncomfortable-making and maybe not ok?
I say that with a lot of affection for Ruby though!
I came to largely the same conclusions, but instead of forwardable, I wrote a new library called superdelegate that is, IMO, more explicit [2]
1: https://brianschiller.com/blog/2019/05/03/two-sorted-lists 2: https://github.com/bgschiller/superdelegate
Python is scary sometimes. If it looks like a duck and quacks like a duck and isinstance(duck), it might be an alien masquerading as a duck using metaclasses to accomplish these feats. But with this craziness comes the ability to make a transparent runtime proxy to just about anything in Python, and do so recursively e.g. to track all uses of an object hierarchy.
Definitely agree about metaclass magic being a blessing and a curse. That superdelegate library was fun to write and uses a metaclass to make the API pleasant.
For instance, I've seen instrumentation libraries monkey-patch database cursors with wrappers around those cursors, so the library can detect usage of the cursor without changing its behavior.
Django itself has a LazyObject class, which operates similarly to an ObjectProxy but only evaluates its wrapped initializer when one of its properties is accessed: https://docs.djangoproject.com/en/2.2/_modules/django/utils/...
And I'm using wrapt in a project (which I hope to open source) where, by recursively wrapping the return value of every __getitem__ and __getattr__ with a properly-bookkept proxy object, you can see what subgraph of a complicated object hierarchy was actually used by a function call (say, the rendering of a Django or Jinja template). Possibilities of such a transformation are endless!
http://docs.groovy-lang.org/2.4.9/html/gapi/groovy/lang/Dele...
In composition (and its on-steroid cousin, delegation), the component/delegate can't "call back" into the aggregating object.
Of course, this additional power can be misused, but it's what should inform the choice between inheritance and composition. Use the least powerful thing that will work — so composition if you don't need to call back into the aggregating object.
It can if you design it to take a pointer to the aggregating object. Pass this or self or whatever keyword your language uses to the component/delegate and then it can call back to the aggregating object through an explicit pointer. This is more explicit than calling through the object's vtable, which makes the code easier to read IMO, e.g., foo.bar() instead of bar().
Yep, and sometimes it's worth it to do it like that if only to cleanly separate concerns.
I can't think offhand of an example to illustrate when you would like this "call back" functionality in a way that you can't anticipate when you design the component object. Do you have a killer-app for inheritance?
e.g. the component manages some kind of list, and the content of this list has to be kept in sync with some field in the aggregate.
No example is going to be perfect, because if you have full control over both classes, well then you can always change their interface in a way that it isn't required anymore. One need to consider the reason the thing should be a component in the first place (maybe the pattern is reused in multiple places) and other external and/or historical constraints on the code.
On the other hand, the problem that I see with inheritance is that it ties code reuse and subtyping together. I don't see any reason why the two should necessarily be related.
I've been playing around with first class environments [0] lately in g-fu [1], which allow convenient and flexible composition of data and behavior using only what was already there.
I have a feeling Lua might be playing similar tricks with its tables, but I lack enough experience to judge.
Can you explain what this means? Still learning Go. Google didn't help.
The issue is that you can't interface methods from pointers to a contained struct, since it has no idea where it is or how it got there. Instead a pointer to the full struct needs to be threaded all the way down to where the overridden function is called.
I sort of understand why, but this is a major missing piece that makes it very frustrating to add anything but trivial default implementations to interfaces in Go from my experience.
https://www.sicpers.info/2018/03/why-inheritance-never-made-...
It argues that there are three different kinds of inheritance and in OO you often mix them up into one hierachy - which may work in some situations, but in some it just can't. Personally, I've experienced this kind of conflict often enough.
I think the worse part is this plague has descended into other languages, if you want different behaviour for different things (but common in someway) just accept a function into your function & invoke it, tada more efficient dependency injection
If a sole developer is the only one working on it, of course any approach can contain the complexity.
But, if in the language you are using, the alternative to inheritance is composition via code duplication, then I think that's even worse than inheritance, especially once the code is unleashed on a whole team of maintenance developers.
Who says all that duplicated code will be left in its pristine state, and used only for it's intended 'compositional' purpose? People might start hanging special logic in there or whatever...
Generally, for projects with large teams like this, the less code the better, because that means there's less code for them to screw up.¹
If that means using inheritance for reuse a bit even if it's not 'pure' OO or whatever, I'd chose that over duplicating code all over the place.
1: I know Java isn't fashionable, but for many reasons, it's perfect for this kind of project.
"You wanted a banana but what you got was a gorilla holding the banana and the entire jungle." -Joe Armstrong
Patterns like adapter, bridge, and strategy are emensly useful in archetecting software that will last more then the next iteration or 6 months.
Perhaps I havent seen the right resources but so far function programming seem weak to me compared to oop which has things like domain driven design, and a very long list of battle tested design patterns.
> He ended with a Spanish question that was evidently made popular in a US advertisement: "¿Por qué no los dos?", which means "Why not both?". Inheritance and composition are both useful tools; developers should understand when to use each.
But I'm not sure that inheritance is the best way to solve it. You would probably want to use interfaces and static methods instead. Basically I literally can't think of a case that isn't better solved by another way.
Some languages may not give you those other options, in which case, by all means use inheritance. Just make sure you are careful not to shoot yourself in the foot while doing so.
If I want to see what code is using a method I am interested in, Visual Studio shows me all related code. But if other developers overrode that method in their own classes, then in addition to seeing ~5 references I like to see, I have to sift through ~50 other references that are irrelevant to my investigation.
So 5 minutes investigation turns into 55 minutes investigation. As you can see, that "references spam" can easily slow down research and development 10x or more.
Aren't mixins a way of avoiding this problem while using inheritance?
At first there I had some quirks, along the lines of "how do I get thing X from A to B", or "these things are similar how do I share code between them".
Everytime this happened I couldn't help but go through a process of solving the problem in OO and then unwrapping it into a non-OO solution. Which doesn't always turn out well.
Eventually, once I became comfortable with Go, I got to the point where I just code things in the most obvious way possible. This struct has these fields. This function takes x and produces y. I dont try to take a big picture view of the software as a whole, Im just solving a bunch of small localized problems one after the other. Then I refactor periodically to get rid of anything completely stupid, and make sure the big picture looks ok. The name of the language is quite fitting, you just go.
Whereas in OO, for me at least, it feels like im constantly bouncing all around the abstraction layers of your program. Any change I make here in class X could affect these other classes. Class A is dependent on Y, but so is class B. How do I share it between them? Maybe dependency injection? Subclasses? Do I refactor to an abstract class? Wait, should it be an abstract class or an interface, what's the difference again? Is this generic enough? I only need to use this in this one place, but I'll make it generic because "best practices". What if I might need this other subclass eventually but it's not on the spec right now?
I'm obviously exaggerating, but I think most of us have been there. I find I often end up in a competition against myself about being more clever or more reusable with my OO code.
Our job is already hard enough when you have to decide and reason about algorithms, data structures, concurrency etc. The extra layer of code patterns usually just obscures things.
I'm not a complete hater though. Using a well designed OO library can be an absolute delight (PyTorch being a great example). But OO is the kind of thing were its not just garbage in garbage out. The garbage multiplies and creates even more garbage.
Looking at the subject for this post:
Inheritance is a good, straightforward approach when you have multiple related classes which share a lot of code but don't interact directly with other unrelated classes:
class document
{
public function title ()
{
}
public function get_plain_text ()
{
}
}
class word_document extends document
{
public function get_plain_text ()
{
}
}
In a document management application, you might need to represent lots of different kinds of document formats, each with their own specializations, but also with a lot of common attributes too. These document classes might not need to interact directly with a database or a network socket, so a straightforward and traditional class hierarchy would be the natural choice here.But then let's say you wanted to build an abstract data pipe. A data pipe needs to talk to lots of different things; maybe it's a plain old network socket, maybe it's a database engine, maybe it's an API. Here, you get no advantages from using inheritance, because although each data pipe is trying to mimic the behaviors of any other data pipe, under the hood their code is completely dissimilar. You'd end up having to rewrite so much of the functionality that there'd be nothing really for a base class to actually do.
This is where composability and interfaces are the right approach:
class phabricator_datapipe implements datapipe
{
private $_api_client;
public function __construct ($api_client)
{
$this->_api_client = $api_client;
}
public function search ($parameters)
{
// Build a search query out of $parameters specific to
// this API, then:
$this->_api_client->search(...);
}
}
Each datapipe class strictly follows a common interface structure. Dependency injection is used during instantiation to compose the runtime object, so the responsibilities in the datapipe class are limited to translating the application's business needs into the specific structures required by the API, while the API class takes care of authentication and error handling.There is room for both of these approaches in the same application, because they solve entirely different problems. The inheritance of the documents classes solves the problem of dealing with similar-but-different units of data in a maintainable, extensible way. The composable interface of the datapipe classes solves the problem of interacting with completely different external components in similar ways.
This likewise is where the post falls over, IMO. It presents an argument for composition, but is too lazy to provide any of the context that really makes composition look like the right answer. Whether a Car object should be modeled as a child of a Vehicle base class, or whether it should be more of a standalone class with other objects injected into it, depends entirely on whether the application just wants to say:
Vehicle->GetTimeToDestination(...)
or whether the application instead needs to: Vehicle->StartYourEngine(...)
(Aside: I think a major failing of posts and books on programming is using contrived, made-up examples, especially when talking about abstractions like object-oriented programming. Those don't help anybody understand the advantages and disadvantages of different approaches. I'm using some examples from applications I've written.)It the real world, a few edge cases can break down an elegant inheritance hierarchy and composition is often the better solution.
But in the day the main reason VB6 was called a toy language was because it wasn't fully OO, it lacked inheritance.
And in his 1999 book Francesco Balena showed how this handicap could be worked around, using delegation.