I have created my own Tree implementation for various reasons and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised.
In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation.
So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't want to override those methods because they also contained shared logic that shouldn't be duplicated!
The problem can be boiled down to this:
public class Foo {
public String value() { return "foo"; }
public Foo doStuff() {
// Logic logic logic..
return new Foo();
}
}
class Bar extends Foo {
public String value() { return "bar"; }
}
new Bar().doStuff().value(); // returns 'foo', we want 'bar'
The first thing that popped into my head would have a 'create hook' that extending classes could override:
public Foo createFooHook(/* required parameters */) {
return new Foo();
}
Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... wrong about it.
It's like cooking while naked-- it feels dangerous and unnecessary.
So, how would you deal with this situation?