I'd just like to point out, the author isn't demonstrating Composition over Inheritance, but Multiple Inheritance over Single Inheritance. So the whole deliberation later in the video about when to use, or prefer composition over inheritance is kind of pointless, given he's confused about what composition is.
Merging objects together is essentially a form of multiple inheritance (or more casually: "traits" or "mix-ins"). When people talk about composition they mean one object having other objects as properties and using those "sub-objects" to achieve a higher goal.
The benefit of composition is that every object retains its encapsulation, and you eliminate the risk of collisions that's present when you merge objects (say Cat adds method "kill" and you merge it with Robot which has method "kill"... problem).
EDIT: And one more note. Because JS doesn't support true multiple inheritance, using Object.assign() has another implication, in that instanceof checks won't return true when checking an object against its parent types.
Whether this matters is up to your design, but I wouldn't give it up so easily and say it's useless. Inheritance, mix-ins and composition are three distinct strategies with distinct pros, cons and uses. The issues come from not knowing what their proper uses are.
Great point. Additionally, he is making the assumption that the traits are going to work the same way and require the same code, which is not always true. Maybe the requirement for a MurderRobotDog is to bark robotically, so you'd be back to needing two implementations of bark() anyway.
Like you say the different strategies need to be used appropriately to make the most simple, powerful and maintainable code.
Can we kindly agree to avoid using cat.kill, dog.bark and any kind of zoo animal example when discussing OO design? These kind of things really suck at illustrating anything in practice and leave everyone stuck at the idea of using OOP to "model the real world", without the context that you would find in an actual program, which helps no one. We have no idea of what the purpose of any specific interface is here, so we can't consider things in terms of Liskov substitutability and judge whether there is actually any design flaw by that metric (if both cat.kill and robot.kill just kill something else, and that's what they're supposed to do, that wouldn't necessarily be a problem, especially if you have some way of allowing one to override the other).
It's nice to use cute examples, but they usually suck at revealing design issues that a realistic example (like some GUI code) would.
Can we kindly agree to avoid using cat.kill, dog.bark and any kind of zoo animal example when discussing OO design? These kind of things really suck at illustrating anything in practice and leave everyone stuck at the idea of using OOP to "model the real world", without the context that you would find in an actual program, which helps no one.
Well, I fully agree, but as we're commenting his examples, I have no choice. Address that to him. :-)
BTW, I actually initially thought he's ironic, because the "Cat extends Animal" is a well-known tired cliche from OOP tutorials. But then he went with it.
"Concatenative prototyping" and "mix-ins" are aliases in the context of JavaScript.
When it comes to composition, there are only two types of composition I'm aware of: functional composition and object composition. And mix-ins are neither kind, so it's not composition.
Are you willing to demonstrate a kind of "mix-ins" which are not "concatenative prototyping" in JavaScript? If you can, I'd be glad if you paste a snippet here & show us all. If you can't, it may be you're being excessively pedantic.
JavaScript does not support mix-ins or traits as Self does. They are simulated by concatenating methods to an object used as a prototype. The limitation of this implementation is that changes to a mix-in are not propagated automatically to the augmented prototype.
The point of me differentiating mixins from composition here is because both are possible in the context of JavaScript and are two distinct techniques with distinct properties.
In your case you came arguing mixins in JavaScript are impossible, so we should use another term, despite there's no confusion whatsoever what "mixin" refers to in the context of JavaScript. I also said this is a "more casual" way of referring to this mechanism, referring to popular JS use.
Let's see what Google thinks with a very specific search, to avoid any unintended noise:
Wow. It's been a long time since I have seen Google return zero results. It's probably easier to achieve with quotes but that does not diminish how impressed I am.
Isn't this searching for the exact phrase "JavaScript concatenative prototyping"? If so, then this is deceptive since it doesn't account for congregations of concatenation or synonyms, or even other equivalent phrases or terminology used by the Javascript community that might produce valid results.
The so called "mix-ins" in JS are usually applied to a prototype object, where the author of the article creates a new object every time. I cannot think of a term that is used in the JS community about this type of object creation so I used the one I already knew from the few papers I read on this topic. Also my understandings of the composition in programming suggest me that what the author describes is really composition.
"Don't be excessively pedantic. It's not very charismatic." - being an ass-hole, by describing someone with unpleasant words because of pure ignorance, is not charismatic either.
The so called "mix-ins" in JS are usually applied to a prototype object
Good way to hedge that bet with a "usually" in there. You know it's both ways. :-)
Given a "prototype object" is just another object, and not a special kind of object, nothing stops the author from using his result as a prototype for new instances. Inheriting a prototype is orthogonal to mixing in properties by copying.
Both uses are common, this is why APIs like Object.assign(), jQuery.extend() etc. don't specifically merge into an object's prototype, this is left to the caller to decide.
Also my understandings of the composition in programming suggest me that what the author describes is really composition.
Object composition is a "has a" relationship for objects, as in one or more objects are subordinates and contained by another object. How can I put it so you don't twist my words, let me see... It's basically like a tree of objects:
The author's examples show one object where methods share state. There's no identifiable "has a" relationship between the "composed" objects.
The author refers to these objects as composition:
barker + driver + killer
In fact, the only "composition" that's happening is this:
(murderRobotDog's methods) + state
Which is identical to creating murderRobotDog as a prototype once, and then instantiating it and using "this" for state. Using a prototype means you can monkey-patch the prototype afterwards & affect all instances, but no one in their right mind does that anymore, so for for all practical purposes they're equivalent... except the prototype solution is faster on V8 and SpiderMonkey, among others.
"Don't be excessively pedantic. It's not very charismatic." - being an ass-hole, by describing someone with unpleasant words because of pure ignorance, is not charismatic either.
Well if it's only when it's because of pure ignorance, I'm on the safe side here.
"Both uses are common, this is why APIs like Object.assign(), jQuery.extend() etc. don't specifically merge into an object's prototype, this is left to the caller to decide."
Actually you are right. If we call this technique a "mix-in" for prototypes the same goes for objects not used as prototypes too.
Mix-ins, as in Ruby and other languages that support that feature, are viewed as a type of inheritance. The main difference here, in JS, is that we are augmenting objects by appending functions to them, which are objects too, so an object and its methods can be viewed as a "has-a" relationship. If you know what kind of relation is the one between an object and its methods I would be grateful if you share that knowledge.
I tried to find what name for this type of "mix-ins" is used in other languages or in general but couldn't find any (other than the name I gave earlier). If you know such names once again I would be grateful if you share that knowledge. (and no, they are no real "mix-ins". "fake mix-ins" or "mix-in simulation" might be good names).
What are the benefits mixins have over composition in your opinion?
You can't implement an interface on your object via composition, not directly at least. I'll use TypeScript-like code to illustrate the idea, but it applies directly to JS (with more writing).
Let's say you have this interface for an event broadcaster (the well-known Observer pattern), and a simple default implementation for it:
How can I use this implementation to implement the interface? Three ways:
I can extend SimpleEventBroadcaster
I can compose SimpleEventBroadcaster and proxy the public method addListener().
I can use SimpleEventBroadcaster as a mixin.
The first approach seems to work at first glance, but the moment you want to make an existing class a broadcaster which already extends another class... you can't. Conflict of single inheritance (the same thing the author mentioned). So that's not a good idea.
So let's compose:
class HelloWorld implements EventBroadcaster {
protected eventBroadcaster;
constructor() {
this.eventBroadcaster = new SimpleEventBroadcaster();
}
public addListener(eventName: string, eventHandler: Function) {
return this.eventBroadcaster.addListener(eventName, eventHandler);
}
}
This is fine, we didn't have to extend SimpleEventBroadcaster, and we didn't have to reimplement it.
This is a perfectly good place to stop in many cases, especially as is here, with one public method. But what if we have 5-6 public methods? Writing those proxies can get annoying at scale.
So we can use a mixin, and our code will become shorter, just one line to mix things in:
class HelloWorld implements EventBroadcaster {
mixin SimpleEventBroadcaster;
}
This, again, is a good place to stop. We removed a lot of boilerplate (especially if we had a lot of public methods to proxy), it works and we're good.
But now we risk collisions from the mixin: its non-public methods and properties are embedded onto our object and we don't really need that. We only need the public methods of the interface, nothing else.
We also lose the ability to have configure SimpleEventBroadcaster during its construction, or have it injected from outside, say via the constructor. This is not good for flexibility.
This is why I like to go for a hybrid approach. A mixin... which implements the proxy methods for a composed object of my choice, to expose it as an interface on my object. This ends up looking like this:
Now we control the construction of SimpleEventBroadcaster (or we can have it injected from outside), but we don't need to write the proxy methods in every object. Again, this becomes more useful when you have plenty of public methods to proxy, not just one, but you get the idea.
I use mixins rarely, and I tend to use them in that last way the most. Basically as a shortcut to save on boilerplate for exposing composed objects. Best of both worlds.
A good rule of thumb is to only mix-in objects that you control. So, say, you may compose objects from other libraries, as composition is less fragile, but mixins and inheritance in general are more fragile, so it's best not to extend & mixin "distant" objects which might change unexpectedly (or can't change when you need them to change).
BTW, if it's unclear how parts of this pseudo code looks like in plain JS, please ask me, but I think it's clear. I think the pseudo-code is cleaner to illustrate the concept.
But what if we have 5-6 public methods? Writing those proxies can get annoying at scale.
Isn't this just a weakness in our means of expressing the concept of forwarding a message to a member? If we're implicitly limiting the discussion to JS, ok. But considering all possible languages, we could have something like:
class HelloWorld implements EventBroadcaster {
compose eventBroadcaster;
constructor() {
this.eventBroadcaster = new SimpleEventBroadcaster();
}
}
where the "compose" keyword would create a member and also proxy methods for its public methods (or maybe just for a specified set of methods). Another option would be to allow something like:
class HelloWorld implements EventBroadcaster {
protected eventBroadcaster;
constructor() {
this.eventBroadcaster = new SimpleEventBroadcaster();
}
notUnderstood (method m) { eventBroadcaster.m(); }
}
If we have multiple objects we might forward to, we could also decide where to send a particular method, or try several destinations if the first doesn't succeed.
From where I'm standing it looks like mixins aren't better than composition so much as mixins are better supported than composition in some languages.
From where I'm standing it looks like mixins aren't better than composition so much as mixins are better supported than composition in some languages.
I didn't say mixins are better, I was asked "what are the benefits mixins have over composition", so the point of my examples was to show mixins and composition have different strengths that can be complementary, so you can combine both to achieve great results.
I don't see them in opposition to each other (when used right). I prefer composition, and I reduce boilerplate with mixins I keep close-by (in the same project), so I can refactor the mixins and the classes that use them together.
Now, do I think I'd be neat if we had a quick syntax to expose composed object methods via proxy? Yep. I've thought a lot about this.
But in the big picture it's just a special case, because a direct proxy method is not the end of the story. You might want to decorate that proxy method with additional logic (say, echo to console.log every time HelloWorld's addListener is called), or use different broadcasters for different events (so we'd have a switch...case in our HelloWorld's addListener, delegating to different broadcasters depending on the eventName), and so on.
class HelloWorld implements EventBroadcaster {
protected eventBroadcaster;
protected eventBroadcasterDebounced;
constructor() {
this.eventBroadcaster = new SimpleEventBroadcaster();
// Debounces events triggered within the span of 20ms.
this.eventBroadcasterDebounced = new DebouncedEventBroadcaster(20);
}
public function addListener(eventName: string, eventHandler: Function) {
if (eventName === 'changed') {
this.eventBroadcasterDebounced(eventName, eventHandler);
} else {
this.eventBroadcaster(eventName, eventHandler);
}
}
}
Kind of an invented use case, but you know such situations occur a lot in practice. Now, you can have such extended logic in a mixin and share it among a few classes, while the specialized "compose" solution can't do that1 . So, mixins remain useful, in select cases. Nice tool in the box, as long as we don't abuse it.
The good general starting point is composition. And then whether we expose methods manually, via mixins, or via specialized syntax like you propose, is a detail that simply saves on a bit of a boilerplate (if used wisely) but keeps the core idea the same.
1 To be fair that could easily be refactored by decorating the eventBroadcaster directly with a pattern-matching aggregator (or something similar):
class HelloWorld implements EventBroadcaster {
compose eventBroadcaster;
constructor() {
this.eventBroadcaster = new MatchEventBroadcaster({
// Debounces "change" events triggered within the span of 20ms
'change' => new DebouncedEventBroadcaster(20),
// Everything else.
'*' => new EventBroadcaster()
});
}
}
... but it's hard to come up with great examples on the spot. :-)
85
u/[deleted] Sep 24 '15 edited Sep 24 '15
I'd just like to point out, the author isn't demonstrating Composition over Inheritance, but Multiple Inheritance over Single Inheritance. So the whole deliberation later in the video about when to use, or prefer composition over inheritance is kind of pointless, given he's confused about what composition is.
Merging objects together is essentially a form of multiple inheritance (or more casually: "traits" or "mix-ins"). When people talk about composition they mean one object having other objects as properties and using those "sub-objects" to achieve a higher goal.
The benefit of composition is that every object retains its encapsulation, and you eliminate the risk of collisions that's present when you merge objects (say Cat adds method "kill" and you merge it with Robot which has method "kill"... problem).
EDIT: And one more note. Because JS doesn't support true multiple inheritance, using Object.assign() has another implication, in that instanceof checks won't return true when checking an object against its parent types.
Whether this matters is up to your design, but I wouldn't give it up so easily and say it's useless. Inheritance, mix-ins and composition are three distinct strategies with distinct pros, cons and uses. The issues come from not knowing what their proper uses are.