Assume the following:
class Foo {
public function foo1() {...}
public function foo2() {...}
}
class Bar {
public function bar1() {...}
public function bar2() {...}
}
Classically, when composing a class of these two, that delegates calls to them, it would look like:
class FooBar {
var foo:Foo;
var bar:Bar;
public function foo1() { foo.foo1(); }
public function foo2() { foo.foo2(); }
public function bar1() { bar.bar1(); }
public function bar2() { bar.bar2(); }
}
There is no syntactic construct to support what you are doing. For every call you want to delegate, you will have to write the same thing over and over again.
Languages that use message passing, such as Ruby, Smalltalk and Objective-C, work around the need for that, by invoking a specific method in response to unknown messages.
It looks something like this:
class FooBar {
var foo:Foo;
var bar:Bar;
override public function handleUnknownMethod(name:String, args:Array) {
if (foo.hasMethod(name)) foo.invoke(name, args);
else if (bar.hasMethod(name)) bar.invoke(name, args);
else super.handleUnknowMethod(name, args);
}
}
This is "better" in the sense that you don't have to do this for every single method. This makes composition less costly and code sharing easier.
Note that this is also not syntactic delegation. What this is, is deferring handling of calls to undefined methods to runtime, which means you can use the language itself to handle them.
Syntactic delegation would be something like:
class FooBar {
@forwardAll var foo:Foo;
@forwardAll var bar:Bar;
}
That would be a syntactic sugar the compiler would resolve by generating a public method for every public method in Foo
, that would merely delegate the call to foo
and would do the same for bar
/Bar
.