• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Refactor code written using many switch cases

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic