Consider the following example where the classes TextFile
, XmlFile
, HtmlFile
, ShellScriptFile
, et cetera, are all subclasses of the class SimpleFile
. I am writing a class FileOperations
, which has a method that searches the contents of a generic file depending on its type.
Following is a code sample:
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
}
...
}
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 File
class or its subclasses.I cannot write to them.
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.
Else, if I am stuck with this structure, then is instanceof
the fastest operator in Java? What are its implications on performance?
Would it be better to use getClass()
or isAssignableFrom()
for the above case?
I appreciate your comments or suggestions!