I mostly come to prefer composition, this approach apparently even has a wiki page. But that’s in part because I use Rust that forbids inheritance, and don’t have such bullshit (from delegation wiki page):
classA {
voidfoo() {
// "this" also known under the names "current", "me" and "self" in other languagesthis.bar();
}
voidbar() {
print("a.bar");
}
}
classB {
private delegate A a; // delegation linkpublicB(A a) {
this.a = a;
}
voidfoo() {
a.foo(); // call foo() on the a-instance
}
voidbar() {
print("b.bar");
}
}
a = newA();
b = newB(a); // establish delegation between two objects
Calling b.foo() will result in b.bar being printed, since this refers to the original receiver object, b, within the context of a. The resulting ambiguity of this is referred to as object schizophrenia
Translating the implicit this into an explicit parameter, the call (in B, with a a delegate) a.foo() translates to A.foo(b), using the type of a for method resolution, but the delegating object b for the this argument.
Why would one substitute b as this when called from b.a is beyond me, seriously.
What no, inheritance is not for code sharing
Sound bite aside, inheritance is a higher level concept. That it “shares code” is one of several effects.
The simple, plain, decoupled way to share code is the humble function call, i.e. static method in certain langs.
I mostly come to prefer composition, this approach apparently even has a wiki page. But that’s in part because I use Rust that forbids inheritance, and don’t have such bullshit (from delegation wiki page):
Why would one substitute
b
asthis
when called fromb.a
is beyond me, seriously.