title: Java code refactoring: multiple instanceof operator usages
body: <p>Consider the following example where the classes <code>TextFile</code>, <code>XmlFile</code>, <code>HtmlFile</code>, <code>ShellScriptFile</code>, et cetera, are all subclasses of the class <code>SimpleFile</code>. I am writing a class <code>FileOperations</code>, which has a method that searches the contents of a generic file depending on its type.</p>
  
  <p>Following is a code sample:</p>
  
  <pre><code>public searchFile(SimpleFile targetFile, String searchStr) {
       if (targetPage instanceof HtmlFile) {
           // search html file
       }
       else if (targetPage instanceof TextFile) {
           // search text file
       }
       else if (targetPage instanceof XmlFile) {
           // search xml file
       }
       else if (targetPage instanceof ShellScriptFile) {
           // search shell file
       }   
       ...
  }
  </code></pre>
  
  <p>This structure smells bad to me. I am aware that this is the best case for polymorphism. But I do not have control over the <code>File</code> class or its subclasses.I cannot write to them.</p>
  
  <p>Is there another way to go about cleaning this mess? Because the if-else structure is going to keep increasing as I add support for different file types.</p>
  
  <p>Else, if I am stuck with this structure, then is <code>instanceof</code> the fastest operator in Java? What are its implications on performance?</p>
  
  <p>Would it be better to use <code>getClass()</code> or <code>isAssignableFrom()</code> for the above case?</p>
  
  <p>I appreciate your comments or suggestions!</p>