• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Refactor code written using many switch cases

 
Rahul.v Joshi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic