4 ms·
Traditional class-based inheritance is an antipattern compared to composition because the child class's API is tightly coupled to its parent: multiple inheritan
by jhanschoo 8y ago
Traditional class-based inheritance is an antipattern compared to composition because the child class's API is tightly coupled to its parent: multiple inheritance of implementations is a mess to reason about, and single inheritance unduly privileges a single parent object that makes refactoring hard when the API of the child or parent has to change.
Composition does not face these issues because instead of a parent class, the outside class's API is not beholden to the inside class's API.
Similarly, in prototypal inheritance, you get to specifically control API by binding or calling 'this' to any choice of object, or select methods to put in other objects, or even replace a method of an object with another method of the same name at runtime, or declare new fields and methods on objects at runtime. This makes prototypal inheritance very open for extension in a way that class-based inheritance cannot be. The downside to this is that JS does not have language features that sufficiently guarantee that an object is closed for modification: in class-based languages classes are a language feature that give a sort of guarantee about the API of an object, but JS objects have no mechanism as powerful as that, and you will need to roll your own. Hence the eventual development of languages and extensions to JS like TS, Reason, Flow that offer these guarantees that transpile to JS.
- zeroname 8y ago> Similarly, in prototypal inheritance, you get to specifically control API by binding or calling 'this' to any choice of object, or select methods to put in other objects, or even replace a method of an object with another method of the same name at runtime, or declare new fields and methods on objects at runtime. None of this sounds like a good idea to me.
- jhanschoo 8y agoIndeed it isn't, and is very lousy to reason about with... until you avail yourself to the sophisticated type systems more commonly found in ML and Haskell through, say, Flow or TypeScript that gives you good guarantees through static analysis as you write.