Re: Chained call pattern with inheritance, polymorphism and generics...
Daniel Pitts wrote:
Anyone have a suggestion for a more elegant solution?
Well, there's always
@SuppressWarnings("unchecked")
public T something ..... {
.....
return (T)this;
}
but you might find the need to @SuppressWarnings icky.
You can make it a bit more hygienic, and avoid suppressing more warnings
than you want to, by making a separate "returnThis()" method:
public T something ..... {
.....
return returnThis();
}
public T other ..... {
.....
return returnThis();
}
@SuppressWarnings("unchecked")
public final T returnThis () {
return (T)this;
}
That quarantines the ickiness in a single method in the base class.
Then there's delegation: a single concrete (even final) type implements
the methods that return "this" and whatever others, but punts to a
delegate passed in by constructor; the delegate is an instance of a
polymorphic type (possibly even an interface type). This separates two
concerns into separate classes -- the polymorphic implementation of all
the variable stuff, and the "this-returning behavior" and possibly some
other constant behaviors.
public final class BaseBuilder<T extends Whatever> {
private final BaseBuilderCore<T> bbc;
public BaseBuilder (BaseBuilderCore<T> bbc) {
this.bbc = bbc;
}
public BaseBuilder something (Object param) {
bbc.something(param);
return this;
}
public BaseBuilder other (Object param1, Object param2) {
bbc.other(param1, param2);
return this;
}
public T build () {
return bbc.build();
}
}
(Note: now parametrized on the type of the thing built, which may not be
necessary. The delegate is likewise parametrized.)
Delegation more generally is *very* useful for dodging certain issues
raised by type parameters.