3 ms·
> Inheritance gone wrong. If a derived type behaves differently, it should not be a derived type. See Liskov substitution principle. Just because a hash map is
by lmm 7y ago
> Inheritance gone wrong. If a derived type behaves differently, it should not be a derived type. See Liskov substitution principle. Just because a hash map is somewhat like a list of key/value pairs doesn’t mean it should derive from one.
The trouble is that "extends" conflates three different things, and many languages don't offer an easy way to do those things separately:
1. Ad-hoc polymorphism: this thing offers the same interface as this other thing, but with a different implementation
2. Composition: this thing contains this other thing, and uses it to implement its own functionality
3. Delegation: this thing implements this interface by forwarding it to this thing that it contains (possibly overriding some parts)
So you end up with things that need to share implementation accidentally exposing a common interface, or vice versa. Thankfully we're seeing more and more languages offering the option to do delegation more explicitly (Kotlin/Rust-style delegation, Haskell/Rust-style derivation), and to do ad-hoc polymorphism without needing to share implementation (Java-style interfaces, Haskell typeclasses / Rust traits).
- b2gills 7y agoIn Raku those things are also separate. 1. Polymorphism class Example { method be-nice () { 'be nice' } } class Bill-and-Ted is Example { method be-nice () { 'be excellent to each other' } } 2. Composition role Salaried { has $.salary; } role Employee { has $.title; } class Manager does Employee does Salaried {} 3. Delegation class Price { has $.cost; } class Product { has Price $.inner handles( 'price' => 'cost' ); } Any call to the `.price()` method on `Product` will delegate to the `.cost()` method on the inner object.