title: Refactoring huge if ( ... instanceof ...)
body: <p>I'm currently trying to refactor a part of a project that looks like this:</p>
  
  <p>Many classes </p>
  
  <pre><code> B extends A; C extends A; D extends C; E extends B; F extends A; ...
  </code></pre>
  
  <p>And somewhere in the code:</p>
  
  <pre><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;
   ...
  }...
  </code></pre>
  
  <p>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?</p>
  
  <p>My idea:</p>
  
  <pre><code>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}
  ....
  </code></pre>
  
  <p>and instead of the huge if:</p>
  
  <pre><code>oopMagic(x);
  </code></pre>
  
  <p><strong>Edit:</strong> 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.</p>