I am containing the “primary object” (with most of the features) within a “helper object” that will provide convenience methods. I have only an Interface available, aside from a returned object with that interface from a factory method. I am thinking a good way to “extend” this object is composition, but the problem that my superclass must implement the primary object’s interface, which would be about 600 lines of stub code.
Clearly an uncomplicated but verbose solution would be to fill out all the stubs so they merely call the primary object’s methods. Is there a better way than this in Java? In other languages I’m familiar with, there would be ways to do automatic delegation for methods that are not implemented in the helper object.
Example:
class Helper implements Interface {
Primary primary;
Helper(Primary _primary) {
primary = _primary;
}
void helper() {
doStuff();
}
// 500 lines of this
void stub() {
primary.stub();
}
}
Note:
Original plan was to just use regular expressions to replace all the stub TODOs in Eclipse with the actual calls. Will be looking for an Eclipse tool that does this automatically though. Also, looks like extending the interface or using Proxy is better in the end, so will be pursuing that.
There are a few possiblites.
First: Use an abstract implementation that delegates the calls.
Second: Use the proxy (probably cleaner).
See: http://docs.oracle.com/javase/1.5.0/docs/guide/reflection/proxy.html
The invocation handler will handle calls through executing a method that you have coded, an all the others would be delegated to the primary implementation.
Then, you can wrap a code like this in a method or another factory.
Third: Using the IDE to generate the methods (as others pointed out).