Friday, June 24, 2011

Polymorphism and if statements

This post probably falls into the category of 'stating the obvious' and has been covered many times before but I figured I'd put the thoughts rolling around my head up here anyway.

Basically whenever I see a big block of code like this:

Car car

if (car.isBlue()) {
    car.doBlueStuff();
} else if car.isRead()){
    car.doRedStuff();
}

I kind of cringe and wonder if it could be done polymorphically with something like

BlueCar extends Car {
    doStuff();
}
RedCar extends Car {
    doStuff();
}

so the if statement becomes

car.doStuff();


Polymorphism 101.


Obviously things are not always as simple or clear cut as this but big switching if blocks with several branches should at least make you pause and think if this is the best solution.