Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring huge if ( ... instanceof ...)

Tags:

java

oop

I'm currently trying to refactor a part of a project that looks like this:

Many classes

 B extends A; C extends A; D extends C; E extends B; F extends A; ...

And somewhere in the code:

if (x instanceof B){
 B n = (B) x;
 ...
}else if (x instanceof C){
 C n = (C) x;
 ...
}else if (x instanceof D){
 D n = (D) x;
 ...
}else if (x instanceof E){
 E n = (E) x;
 ...
}else if (x instanceof G){
 G n = (G) x;
 ...
}...

Above if-construct currently sits in a function with a CC of 19. Now my question is: Can I split this if-construct up in mutliple functions and let Java's OO do the magic? Or are there any catches I have to look out for?

My idea:

private void oopMagic(C obj){ ... Do the stuff from the if(x instanceof C) here}
private void oopMagic(D obj){ ... Do the stuff from the if(x instanceof D) here}
private void oopMagic(E obj){ ... Do the stuff from the if(x instanceof E) here}
....

and instead of the huge if:

oopMagic(x);

Edit: I cannot change any of the classes (A,B,C,...). Inside the if statements some getters are used to read (never write) data from each object.

like image 915
Chris Avatar asked Dec 28 '22 03:12

Chris


2 Answers

That won't fly. instanceof detects the runtime type of a variable. Polymorphism (select method by signature) depends on the compile-time type of a variable. That is, you'll always get oopMagic(A obj).

As Roger suggested, take a look at the visitor pattern, a.k.a double-dispatch.

like image 111
Little Bobby Tables Avatar answered Dec 30 '22 18:12

Little Bobby Tables


It's hard to tell what would work best since you haven't given any indication what the code is doing, but another option is to add an oopMagic() method to A and override as necessary.

like image 22
Brad Mace Avatar answered Dec 30 '22 17:12

Brad Mace