Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Java architecture is allergic to "switch-case"?

 
Pearlo Muthukumaran
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
SJ Adnams
Ranch Hand
Posts: 925
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
switch case doesn't work on objects. so it is real 'C style' coding.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic