I’m going through Java For Everyone by Cay Horstmann.
I’m a bit confused on when it says:
Don’t Use Type Tests
This is about using instanceof operator for specific type tests in order to implement behavior that varies with each class like (taken straight from the book):
if (q instanceof ChoiceQuestions) //Don't do this
{
//Do the task the ChoiceQuestion way
}
else if (q instanceof Question)
{
//Do the task Question way
}
Apparently this is a poor way to do it as if you have a new class like NumericQuestion added you need to revise all parts of your program that make a type test, adding another case.
It is better to add class NumericQuestion to the program. Nothing needs to change as we are using polymorphism, not type tests.
When ever you find yourself trying to use tyepe tests in a hierarchy of classes, reconsider and use polymorphism instead. Declare a method doTheTask in the superclass, override it in the subclasses and call q.doTheTask()
What I don’t understand is the last paragraph, the one above. Can someone shoe me an example of what it means please? (I’m kind of a visual learner). How do we actually do this without using tyep tests?
The point is that instead of this:
you should do this:
where the
Questionclass contains:and the
ChoiceQuestionclass containsThen, when you get a new class
DrawQuestion, it will containbut none of the code that calls
doTheTask()will have to change! There is no risk, as there is with theif (q instanceof ChoiceQuestions)pattern, of forgetting to add the new logic. And (this is actually the more important part in the long run) all the logic that concerns a specific kind ofQuestionis concentrated in one class rather than spread out across all parts of the app.