This week's giveaways are in the MongoDB and Jobs Discussion forums. We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line! See this thread and this one for details.
Why Java architecture is allergic to "switch-case"?
Joined: Sep 17, 2002
Hi all, What is the exact reason for the avoidance of switch case statements in Java atleast at the High Level Design stage. is the reason mainly attributed to 1. Need for factoring and object-orientation? OR 2. Usage of "switch-case" is having any performance issues? The famous recommendation whenever "swich-case" is encountered for say executing a function based on the "switch" value is to use Command Pattern. Will this not result in introduction of too many classes? Please clarify.... Rgds Muthu
Joined: Sep 28, 2001
switch case doesn't work on objects. so it is real 'C style' coding.
Peter den Haan
Joined: Apr 20, 2000
The usual OO recommendation is to replace switch statements by polymorphism. The Command pattern is one way you can achieve this -- often, you can eliminate it by simply implementing a polymorphic method on existing classes; in yet other cases, double dispatch is a better idea; and finally there are situations in which eliminating a switch would make the code less flexible and clear rather than more (your class bloat concern). It really depends. As usual, the C2 Wiki has some delightful discussions arguing that switch statements are considered harmful and that they smell too. Presumably they never brush their teeth or clean the bath - Peter
Joined: Jan 29, 2003
One reason to avoid switch statements is that when you add a new condition, you have to go into the switch case statement and add code. Most of the other solutions such as command and double-dispatch try to make the code more stable and extensible. That is, you can add new stuff to the system without recompiling all of it. This is important because every modification is a risk of error, and you might not even have the source code. Here's a neat paper on dependencies (that I have recommended about a thousand times lately) http://www.objectmentor.com/resources/articles/oodmetrc.pdf It doesn't cover switch statements in depth, but shows how cool it can be to make code open for extension but closed for modification.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi