redit_10 redit_10 - 2 years ago 75
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 Source

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();
  case FordCar:
  case ToyotaCar:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download