Un-oriented Design

I know that my code is full of such things, good for me Psycho eliminated a very non-java like structure from my code this morning and once more I wish we’d do full code-reviews.


public void setData(AbstractData data)
{
if(data instanceof FooData)
{
this.setFoo((FooData)data);
}
else if (data instanceof BarData)
{
this.setBar((BarData)data);
}
...
}

Yeah I know – now. Don’t ask me when I forgot what java was all about. It’s not even a bug. It’s a flaw.

update well so there was a reason for the construct, because the setData method is called in an environment when there is really nothing known about the data argument. And I really do not want to know. So either I must make big changes to the design or keep the instanceof variant of the method because at one time or another I have to find out what type I have.

The fundamental problem is another: “I forgot what java was all about” and never thought about it when implementing my “design”. It might be a complete mess for all I know.

abstract class AbstractAction { abstract setData(Abstract data); }
class Action extends AbstractAction { setData(AbstractData data){ ...instanceof testing for data... }
class C {
execute(AbstractAction action){
Iterator datalist ....
while(datalist.hasMore()){
action.setData((AbstractData)datalist.next());
...

Please tell me a better solution than the instanceof testing.