by timr · 12y ago · 0 comments
Former biologist here. Actually...most living things do work that way. A human ISA primate. Genetically. Functionally.
If you merely focus on outward behavior, you get to the same place that early biologists got to with what was called "morphological classification" -- you find the weird examples of convergent evolution (e.g. "OMG egg-laying mammal!"), and you're tempted to throw out the whole classification system, even though it mostly works, and the errors are merely distracting from the inherent truth of the idea (that we're all related by genetic phylogeny; we literally share implementation).
Anyway, programmers, learn from biology: when you see these kinds of errors it probably means that you're classifying things incorrectly, not that you should stop classifying altogether.
That being said.
Classifying things using inheritance leads to a software architecture that is difficult to change. This is especially the case if you follow the principal of don't break interface.
In the real world, people can build out classification systems and easily add in edge cases when we find new ways things can be classified. In software, that could lead to a complete change in the software architecture.
All ridiculous discussions of biology aside, having a class based hierarchy is a maintenance issue in comparison to designing classes through compositing. There are 2 ways to design a 'cheeseburger': a) meat sandwich is a super class of burger which is a super class cheeseburger b) meat sandwich which contains, bun, cheese, patty lettuce
B is a more maintainable system and allows for better class flexibility in the design. It avoids having complex bugs where 'meat sandwich' changes some internals and breaks something down the hierarchy chain in some subtle way (for example in releasing a access to a critical resource).
In my limited understanding of biology this works fantastically well. For a platypus, "Is-a" is ridiculously broken, and one would not want to try and reproduce the underlying source code. However for classifying and interacting with the platypus "has-a" warm blood, "has-a" egg-laying-thing (#) "has-a" receptor for x is all we care about.
I suspect that is-a works fine at the cellular level and tends to break higher up - and that is pretty much my experience - in software we want to build Eco-systems - and forget that an individual humans body is more an Eco-system than a single machine.
interesting food for thought
(#) what I said about limited biology
But to begin with, we're not classifying things; we're building them. Software is designed; you don't (or at least shouldn't), construct your programming abstractions by progressively mutating the different parts of your code. Nature had to reimplement flying for the bat, but you don't have to! You get to build a bat by strapping wings onto a rat, and you know how to build wings because you already did it for birds. But the hierarchy system doesn't let you do that; you'll have to do what nature did and completely reimplement flying for the Rodent subclass of Mammal, since Bird is nowhere near it in your hierarchy diagram. That's the essence of the author's point, as I read it.
I suspect Raganwald would probably go a lot further than an OOP+mixin approach (and there is no shortage of good alternatives), but the simplest way around this kind of thing is something like this piece of Ruby:
class Bat
include Flying
include Rodent
include Echolocation
end
You get the idea, and it's pretty easy to port to JS. It also lets you build the griffin and the centaur, because the software doesn't have to follow nature's rules about how to derive one thing for another. Constraining your code's structure to evolution's is-a model is a straight jacket.So that's implementation, but what about interface? We actually do care about outward behavior, and making our interfaces reflect that is important. Morphological classification may not tell you much about how a bat works inside and what other species a bat is evolutionarily close to, but it remains the case that if you want to know what a bat does, flying is a big part of that. What if I want to know whether a given animal can get over my fence? How do I ask if a creature can fly? I don't care at all that bats are closely related to mice because they're acting nothing like mice when zooming over my fence. Do I really add canFly() to some Animal superclass and have flying creatures override it? How many features will I detect that way? But with our mixins, we can just ask if it includes Flying, because the structure of our code captures that. Codifying the structure of your interface into the structure of your classes is part of the point of OOP, but it turns out that interfaces don't fit a simple inheritance mold. So you need more powerful tools to describe that structure.
This issue comes up enough in gaming that the no-hierarchy-lots-of-mixins approach has a name: the entity-component model. I bring this up not because I think the point applies differently to games but because it's a domain where you might actually build a bat.
Finally, how far would we really be willing to take biology's classification-by-implementation philosophy, even if classifying pieces of code were really our goal? We could end up with superclasses like UsesAStar and HashSet. Not really the point of all of this, right?
Long story short: I agree with the article and think the biology doesn't contradict it, but think we should probably stop using evolution as a conceptual model for how we organize our code.
Is this another ad for big design upfront, aka waterfall? It is a nice ideal, but when you get down into it, software really is evolved since requirements are constantly changing and your understanding becomes better.
> You get to build a bat by strapping wings onto a rat, and you know how to build wings because you already did it for birds.
Really you don't. The bat flies quite differently from the bird, with substantially different attributes. Strapping bird wings onto a rat often isn't going to work.
> This issue comes up enough in gaming that the no-hierarchy-lots-of-mixins approach has a name: the entity-component model.
This is actually much older than that (Common Lisp Flavors), and languages like Scala include mixin-like traits, not to mention the work of Bracha and Cook. Inheritance is still heavily involved in that though, it is not "mixins or inheritance" but "inheritance with mixins," it still very much is OOP, and you are still defining a DAG if not tree.
> Finally, how far would we really be willing to take biology's classification-by-implementation philosophy, even if classifying pieces of code were really our goal? We could end up with superclasses like UsesAStar and HashSet. Not really the point of all of this, right?
Why not? Why not classify all of our code at the finest grain we can? Of course, existing languages are poorly suited to that task, but we can always define new languages where this isn't a PITA. Or we could just use machine learning to figure out what the connections are automatically (this will happen eventually, just not for another 10 or 20 years I hope).
Not at all. You won't even know what the right abstractions are upfront. If you want to express the point here in terms of coding process, it's something like "refactor your code into this". That the design emerges iteratively isn't the same thing as saying there's no design. Contrast to evolution, which is not just iterative but also has no design at all. No one gets to sit around and think, "huh, let's reorganize this". Because if they did, maybe organisms in convergent evolution would share code.
Edit, let me try that point again, because I don't think that was very clear. You may design iteratively, but you're still designing. "Oh, these things have x in common, so let me build an abstraction that captures that commonality and have them use it." But evolution can't do that. The only design tool it has is mutating existing code into additional subclasses. You have more tools than that, so as a metaphor evolution's "designs" can be described by simpler ontologies. So why limit yourself to those ontologies? You can think of evolution as having ridiculous limitations on the kind of design work it's capable of, which are independent of the fact that it's iterative.
> Strapping bird wings onto a rat often isn't going to work.
That you have to implement genuinely different things differently is true enough, but not really challenging the point that class hierarchies make encapsulation harder. Also: maybe an engineer would design a bat a bit differently inside so that it could use the avian wing tech? Just a thought.
> Why not classify all of our code at the finest grain we can?
My point there was that if you had choose one axis on which to classify parts of your code, implementation details wouldn't likely be it. That you have to choose is a consequence of the strict single-inheritance model here. Completely classifying a software abstraction is identifying the point n-dimensional space that describes it in terms of all the different ways to categorize it. A fool's errand in general, I suspect, but at any rate not possible under the class inheritance model (single or multiple).
Edits: multiple for clarity
I would claim that our process of building things very much follows the process of evolution even if we have the ability to design explicitly rather than perform random mutations follows by natural selection. Our ability to classify things and carry over implementation fits with this way of building. OOP is not just a way of implementing a design, I would say this is actually secondary: its a way of coming up with a design in the first place where you really don't have it all down in your head before you start coding.
This is what so annoys me about Haskell: it works very well when you can figure out everything before hand; in fact, you are expected to think long and hard about your problems because its language abstractions are very unforgiving otherwise.
Haskell designs are then elegant out of necessity, and this is very limiting when you just need to get something done (aka worse is better). OO implementations are typically over-engineered and less elegant, not because OO thinking is somehow defective, but because elegance is not required to encapsulate complexity and just get something working.
> My point there was that if you had choose one axis on which to classify parts of your code, implementation details wouldn't likely be it. A fool's errand in general, I suspect, but at any rate not possible under the class inheritance model (single or multiple).
Implementation details provide the strongest signals of similarity than artificial interfaces. If you were going to let a DNN or RNN classify your code, it would probably be along this axis as well as with how the code was actually used.
> That you have to choose is a consequence of the strict single-inheritance model here.
I rarely let myself be constrained by single inheritance, even when I'm coding in C# I have my mixin patterns handy (ya, more boilerplate, but I can type fast; all my own languages support mixins).
> Completely classifying a software abstraction is identifying the point n-dimensional space that describes it in terms of all the different ways to categorize it.
I agree, but if we aren't limited by single inheritance (say linearized multiple inheritance via mixins...or gasp...aspects), then this argument no longer holds.
Interesting comment. I have no particular leanings towards any methodology[1], but I do find it useful to understand a situation before presuming to have appropriate ideas about changing it[2].
To many that constitutes big design upfront. So be it. My projects tend to deliver on time, and to budget.
[1] https://www.wittenburg.co.uk/Entry.aspx?id=99bb5987-e08d-4e8...
[2] https://www.wittenburg.co.uk/Entry.aspx?id=46870dcd-70cb-4ef...
The worst projects, with runaway costs, unhappy stakeholders and a real brutal grind for developers had the least requirements planning.
I've seen code design up-front go wrong often enough, but I've yet to see up-front specification and requirements gathering be anything but much more successful than the alternative.
As a matter of fact, knowing you have to deliver C, but then focusing development on A, with an idea that there might be a B, and not putting any real thought into any of them is so so painful IME. Nobody ends up happy. When I hear "iterative development" these days from a developer, I don't hear "pragmatically responding to a change in requirements". I hear "I don't feel like thinking this through, so I'm going to do something I know doesn't meet the requirements first, and we'll rework it at some point".
I've rarely seen core project requirements change much over the course of a project. I've seen developers cargo-culting and generating rework a number of times though.
As an early "Agile" fan, who was a developer when the Manifesto debuted, it's real frustrating that today's development landscape seems to promote the idea that planning is bad and you should just start diving into writing PostIt notes and setting up your first week's sprint without a thought to an overall schedule.
That's not Agile, that's just cowboy coding with the appearance of rigor (IMO). The whole point is to make a plan, research, investigate, get a solid idea of what you need to do, then do it. And while you're doing it, if circumstances change, be prepared to change with them.
> "Responding to change over following a plan".
> "while there is value in the items on the right, we value the items on the left more"
Which totally makes sense. Yes, don't stubbornly insist on delivering a feature the stakeholders don't want just because it's in the plan. And if you have a fixed time budget, yes, focus on the scope that's most important and pick your battles. None of that says "don't plan". "there is value in planning". That is what the Manifesto says! So stop using "agility" as an excuse to do a bad job, generating tons of rework, burning people out, and spending other people's money. There's nothing "agile" about that.
"Iterative Development" is just code for exactly that IME. Kaizen is about improving your process. Not throwing it away.
Sorry if that's a bit too ranty. ;-)
The article was arguing that inheritance is wrong, and using a (broken) biological metaphor to back up that argument. In fact, it's pretty easy to argue that the coding example was broken in the same way -- you could resolve the stated dilemma (using a transaction history instead of a current balance) by creating a new subclass at some level of the original hierarchy. And if you can't do that, you possibly had a broken design from the start, or you really did need to re-work all of your original code to adopt to the new implementation (or both).
Mixins don't make your code magically adaptable to re-implementation. They force you to encapsulate more stuff, but you could just as easily design an inheritance hierarchy with the same properties (i.e. make subclasses all work with private data via protected methods), or you could adopt a hybrid approach -- for example, one could imagine making the class hierarchy in this post using a Strategy pattern to implement the actual tracking of balances.
Usually, when people have an axe to grind with inheritance (or encapsulation), it's because they've run into the problem that code design is subjective and imperfect. Programmers don't like that much, and it's more fun to blame the tools.
Do you have any other good examples of situations where it makes most sense to use inheritance?
These turn out to be remarkably tricky questions which is why Linnean classification is not as stable as we would like to believe..... It mostly works, but only to some extent, which is the problem.
All models are wrong. Some are useful. As you pointed out, there is no such thing as a species in the real world -- it's just in the model that there's a species.
The model has been so successful that, unfortunately, it's treated as "true" by many people, which means that 1) they don't understand its limitations, and 2) they don't work to improve it.
+1, I'm glad you mentioned this.
The dissonance comes in with timeless ontologies. Ontologies whose members don't share a common ancestor. Rather, the members share traits. Inheritance works in some cases, but not in all. Once it stops supporting all cases, it causes unnecessary complexity to the model.
You're confusing the model with reality. The classification system is simply a model that describes many things correctly, and many other things incorrectly. If you feel that there is inherent truth of the idea, then that probably means that it's a really good model. But it's still just a model.
For example, you said that a human ISA primate. But that's only in the model. Outside of the model, there is no such thing as a primate. Reality is far more complicated, and "human ISA primate" misses many corner cases. You also said we literally share implementation, which, again, may be useful but isn't quite true, whether one is talking about DNA, epigenetics, or macroscopic properties.
But that's okay -- it's still a good model, because it's useful and simple and easy to understand and works much of the time. We just have to be careful not to forget its limitations and applicability.
No one is releasing ‘Biological life forms 2.0’ and worrying about whether penguins stop working.
The problem is that writing reusable software is hard, inheritance is a really easy way to introduce reusable code into your software but a bad abstraction or base class has viral effects.
what is the morphology of a class? I would argue that it is the interface. That is the part that determines the form that other programs interact with. that's the part that actually matters for object oriented design.
so while you're right that in biology morphological classification is a distraction that belies the existence of deeper relationships, in computing morphological classification is actually the most important part and what we should focus on.
This is breaking the Liskov Substitution Principle[1]. By saying that Penguin is a subclass of Bird, you're implying that I should be able to stick a Penguin into any code that expects a Bird, that code will just work, without it having to care about the particularity of that Bird actually being a Penguin.
[1] http://en.wikipedia.org/wiki/Liskov_substitution_principle
[edit: grammar]
Overall agreed, though. This ties into timr's point that if there are errors in your classifications, then your class hierarchy is incorrect.
I think sticking to the 'age old wisdom' of using direct inheritance for IS-A relationships and composition for HAS-A is still the right way to go. It's been tested, it works, and using HAS-A for everything makes for less understandable code imo. Often you can fix an IS-A by simply refactoring your graph with a better understanding of the problem space - as it turns out biologists have done as well.
A lot of the time, you'll think you're defining a superclass when you start writing things like "Square IS-A Shape; Rectangle IS-A Shape". But Shape will turn out to not define any common behavior, just a category you want to restrict your inputs and outputs to; and you'll want to be able to assert that anything is, in addition to whatever else it is, a Shape. So shape is an interface.
A lot of the time, you'll think you're defining a superclass when you start writing things like "User IS-A Person; ProjectOwner IS-A User". But it'll turn out that you want to keep People around even when they stop being Users, and to keep Users around even when they stop being ProjectOwners. So you'll rearrange things and find that you're now asserting "User IS-A Role; ProjectOwner IS-A Role; Person HAS-MANY Roles." And Role turns out to be, again, an interface.
The only example I can think of that does fit single-inheritance is when modelling objects that directly express a genealogy. For example, GithubForkOfProjectA IS-A ProjectA, or Ubuntu IS-A Debian. But these aren't typically things you'd express as types; they're just instances (of, respectively, GithubProject and LinuxDistribution.) Each instance HAS-A clonal-parent-instance.
I guess there's one possibly-practical use of inheritance which I've nearly implemented myself: if you force your database schema migrations to always follow the Open-Closed Principle, and you want to migrate the rows of a table as you encounter them to avoid taking the DB offline, then you could have two separate models for a Foo table, FooV2 and FooV3, where "FooV3 IS-A FooV2". Each row has a version column, and is materialized as the model corresponding to that version. Your code that expected FooV2s would then be satisfied if it was passed a FooV3.
Does anyone actually do this, though? I don't just mean "row-by-row migrations", I mean the "with two models, one version inheriting from the other" part. And, if so, what do you do when you make a change to a model that doesn't obey the Open-Closed Principle: where FooV3s break the FooV2 contract?
I think the right solution is simply to have firmer constraints about the relationships between parent and child classes - just like decoupling a class's implementation from its interface, it should be possible to separate out the interface it exposes to child classes as well. The one library/framework I've seen that does this really effectively is Wicket - it makes extensive use of final classes, final methods, and access modifiers to ensure that when you need to extend Wicket classes you can do so via a well-defined interface that won't break when you upgrade your Wicket dependency. It works astonishingly well.
But the Decorator pattern is not "inheritance without the syntactic sugar." Decorated objects, unlike subclass instances, are allowed to break the contract of the object they decorate: they don't have to claim to obey any of its interfaces, they can hide its methods, they can answer with arbitrarily different types to the same messages, etc.
If a language made defining decorators simple, I think it'd remove a lot of what people think of as the use-case for inheritance. (I mean, you aren't supposed to use inheritance for Decorator-pattern use-cases--it will likely break further and further as you try--but people will keep trying as long as the first steps are so much easier than the alternative.)
In case you're hankering for a language that makes delegated composition easier, Go's "embedded fields" are sugar for exactly that: http://golang.org/ref/spec#Struct_types
For example: HTTPResponseHandler IS-A TCPResponseHandler because its primary role requires a TCP socket on construction. The only inherited methods should be management of the data from construction.
Problems with this only arise when people use subclass to gain the interface but not the data. You should never need to do this and it's a problem with using classes instead of interfaces for your parameter declarations – it's not a problem with class inheritance.
Shape can lay itself out with regards to its enclosing rectangle for example.
From my experience, using IS-A only works on simple concepts, and almost never on more than 2 layers. But it's still useful.
I suppose that if languages had the same "automatic function redirection" to sub-components, such as Golang, then people would use composition a lot more, though. That's actually the thing that seduces me the most about this language.
How so? I mean, sure, Shape can declare, say
bool is_inside(Rectangle enclosing_rect)
...but how would Shape know how to calculate that? It'd be an abstract method. All of Shape's methods would be abstract methods. Thus, a Shape is an interface: a contract an object makes with the system to say that it has a given API.Perhaps I'm missing something, but I think the article makes the point that single inheritance results in a tree structure, not a DAG. That aside, I feel it's unfortunate that he chose to illustrate his point by way of analogy, as it seems some of the arguments here are refuting the analogy and not his original point.
My personal experience has been that as software grows in complexity, isa relationships tend to fall apart. Generally this is because although they have some characteristics in common, they only have SOME characteristics in common. Further, the more the tree grows in breadth, the fewer the shared characteristics there are. Over time, this overlap becomes so small as to utterly rob the isa relationship of meaning. Saying X is a Y simply means that (generally for historical reasons) you chose to emphasise the commonality of X and Y over the equally valid relationship that X is a Z. Oh and often an A and a B.
I say grows in breadth because, with inheritance, having a tree grow in depth suggests specialisation in each branch WITHOUT behaviour shared between some (but not all) nodes in different branches of the tree. In practice I've found this happens so infrequently as to barely worthy of consideration.>> when you see these kinds of errors it probably means that you're classifying things incorrectly
I accept that this may be entirely true. However, I have seen significant resources (time, mental effort, etc) dedicated to discovering the correct classification - although that presupposes that there is a correct classification, so perhaps I should say more useful classification - of a class hierarchy in a project, and have not been able to find something adequate. Whether this was due to our stupidity, or whether this is because there is indeed no clear way to express the relationship in hierarchical terms, the fact remains that it made inheritance an unsuitable way for us to model our problem domain.
> Often you can fix an IS-A by simply refactoring your graph
Your use of the word suggests to the reader that this is an easy undertaking. In practice I have found this is often note the case. Saying that we CAN refactor the inheritance tree doesn't mean that it is simple to do, and I posit that by the time you have learnt enough about your domain to recognise you have modelled it incorrectly, the hierarchy is of such complexity that this is generally a very difficult undertaking. Again, I'm not arguing against refactoring, but rather that refactoring inheritance hierarchies is often difficult.
I think ericHosick (above/below?) says it best:
> In the real world, people can build out classification systems and easily add in edge cases when we find new ways things can be classified. In software, that could lead to a complete change in the software architecture.
My experiences are obviously anecdotal, but since I find that I - and many other software developers whom I talk to - struggle to make domain modelling using class hierarchies work, his argument that is inherently flawed rings true.
I disagree. I think it's extremely fortunate. You are acting as if you know all the answers - and you may even think you know all the answers - but I think refusing to consider that biology went through something similar (and I bet there were numerous biologists who wanted to destroy the classification system as it was 'wrong') and found an answer that differs with yours does not mean there is no link. You could be wrong too. Maybe we are missing tools to allow us to alter our classifications later and that classifications are the best solution when given the correct tools.
this._currentBalance = this._currentBalance - cheque.amount();
"In JavaScript (and other languages in the same family), classes and subclasses share access to the object’s private properties."Self-encapsulation ensures internal variables are only directly referenced twice: via accessors. This adheres to the DRY principle. The above line should be written:
balance( balance() - cheque.amount() );
Or more explicitly as: setBalance( getBalance() - cheque.amount() );
Even if the superclass is later modified to use a transaction history, which would violate the Open-Closed Principle, the subclasses would continue to function correctly. (The transaction history would be implemented inside the accessors, making the additional code transparent to subclasses.)Source code that eschews self-encapsulation will be brittle. Developers must grok the DRY principle. Code that directly sets or retrieves internal variable values in more than two places should be refactored to eliminate the duplication.
Also, the Account class is incomplete. The Account class should have a withdraw method to mirror the deposit method. The ChequingAccount would overload the Account's withdraw method to take a cheque object, such as:
ChequingAccount.prototype.withdraw = function (money) {
super.withdraw( money typeof Cheque ? money.amount() : money );
return this;
}
I am unfamiliar with the JavaScript OO syntax to call the superclass, but this revised design is otherwise sound. In this way, the parent class can vary its account balance implementation (e.g., introduce a transaction history) without affecting its children.I think this touches on a big difference between science and software. In science, models are not "thrown away" because there is no need to throw them away. Multiple models can exist side-by-side, whereas it seems to me that this is not the case in software.
For example, Newtonian mechanics were great for a really long time. Then relativity came along and was found to be superior to Newtonian mechanics in some situations. Does that mean that we threw out Newtonian mechanics? No! It's still a useful model, regardless of the fact that it's wrong in some cases.
The point I'm making is that biology uses "single inheritance" not because it's right, but because it's useful in some cases. In other cases, where it breaks down, you will be forced to use a different model.