Meaningless Drivel is fun!*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Refactor code written using many switch cases Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Refactor code written using many switch cases" Watch "Refactor code written using many switch cases" New topic
Author

Refactor code written using many switch cases

Rahul.v Joshi
Greenhorn

Joined: Sep 20, 2007
Posts: 2
Hi,
I have to reactor code written using switch case. The scenario is as:
case 1:
reset some instance vars of a class , class has many instance vars
case 2:
reset some instance vars of a class , class has many instance vars
case 3:
reset some instance vars of a class , class has many instance vars
case 4:
reset some instance vars of a class , class has many instance vars
.
.
.
case 20:
reset some instance vars of a class , class has many instance vars


Can anyone suggest an optimal way to replace this procedure oriented logic using OOPS concepts/patterns.
Thanks,
-Rahul.
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1282

Hi Rahul,

the reason for such lengthy switch-case or if-else clauses is often that the class where they occur is not really responsible for the functionality!

In you concrete example you should no let the switch-case clause do the reset but instead you should tell the corresponding object to reset itself. Of course the objects then should have a common parent class or better implement a common "reset" interface so that you can call for example reset() on any object no matter what concrete type it has. Therefore there will be no need to use a switch-case statement. Simply call "someObject.reset()" and let the object itself to the necessary cleanup.

I hope this helps a little bit to understand the typical cause for such a code smell ;-)

Marco
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Refactor code written using many switch cases