Brandon DuRette wrote:Per Campbell's reply, you may use either method that you choose, depending on the specificity of the class name you wish to use in your conditional logic. However, I would caution you that this approach is very brittle. If possible, consider other approaches.
Are there properties/attributes of the subclasses that determine the appropriate behavior? Is the conditional logic you are implementing more suited to be in each of the subclasses?
The problem with dispatching on the instances' class names is unless the class hierarchy is frozen (and the leaf classes are final), your code breaks when the class hierarchy changes. Additional subclasses of the base class could be introduced that you do not handle. If they're not final, additional subclasses of the subclasses could be introduced. Consider the following:
With this class hierarchy in place, assume the following conditional logic:
You write your tests and everything appears to be working just fine. Then I come along and introduce the following and your code breaks:
If instead, your code used getSides() (or any other attribute) to determine the behavior, then your code is much less likely to break. That said, how you ultimately implement your solution is up to you. I just wanted to make you, and others who will read this thread in the future, aware of the issues with using class names in conditional logic.
So, the question is, given that you can change all the classes in this class hierarchy, why not add the functionality you need to a and all of its subclasses, rather than trying to dispatch on a name. This is the polymorphic approach.