When using static programming languages such as Java, often time I have seen people writing methods that accept Object as a parameter. These methods typically don't really work on any Object, but works with multiple types of classes that don't have any common base class. Here's an example of such a method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void processMessage(Object message){ | |
if(message instanceof CleanFloor){ | |
((CleanFloor) message).cleanKitchen(); | |
} | |
elsif(message instanceof LaunchRocket){ | |
((LaunchRocket) message).shootToMoon(); | |
} | |
} |
process
method actually expects one of CleanFloor
or LaunchRocket
instances. However, since the two don't have a common subclass, it falls back to an Object type. And that results in the smelly code as you see in the example.An ideal solution would be to change the design of the classes so that you can either use a common base class or a generic method. But if you can't just do that
Get rid of the instanceof anyway!
However, this doesn't need to be smelly. Turning to basics of OO programming concepts, you will recall that there's this thing called method overloading that is specifically there to solve this very problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void processMessage(CleanFloor cleanFloor){ | |
cleanFloor.cleanKitchen(); | |
} | |
public void processMessage(LaunchRocket launchRocket){ | |
launchRocket.shootToMoon(); | |
} |