redit_10 redit_10 - 7 months ago 7
Java Question

Why is the switch statement to be avoided in Java?

One of my teachers said that we should avoid using the switch statement.
Why? what's bad about it?

Answer

Your instructor may have been trying to keep you guys from falling into a situation where you use a switch statement as a crutch! There are situations where they are appropriate, but often they are used to hard-code something that is better-handled with polymorphism.

For example:

Car c = getCar();
switch(c){
  case FordCar:
    driveFordCar();
    break;
  case ToyotaCar:
    driveToyotaCar();
    break;
  default:
    break;
}

would be better-handled by putting an abstract method driveCar() in the abstract class or interface Car, then implementing it in FordCar and ToyotaCar. If you want to add support for Volkswagen cars, think about how much cleaner it would be to add an implementation for driveCar to your new VolkswagenCar class (the compiler will complain if you don't!) instead of having to remember to update your case statement.

Comments