• 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

question about refactoring conditional logic

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello:

I'm having a hard time with implementing the notion of getting rid of some "if then else" hell.

Given the following code sample:

if (i = 1)
{
method1(i);
}
else if (i = 2)
{
method2(i);
}
else if (i = 3)
{
method3(i);
}
else (i = 4)
{
method4(i);
}

I looked in Fowler's "Refactoring"... but replace conditional with polymorphism doesn't seem to apply -- these aren't classes, they're method calls. I looked at http://polygoncell.blogspot.com/2008/07/as-many-people-already-met-there-are.html and all they did was replace the if block with switch. That doesn't really eliminate the conditional now does it? I also read somewhere else that I could use a map. The dilemma is my conditional calls methods, not make assignments... so something like this really doesn't work:

HashMap commandMap = new HashMap();
commandMap.put(1, method(1));
commandMap.put(2, method(2));
commandMap.put(3, method(3));
commandMap.put(4, method(4));

So while I'm NOT asking the forum to do my work for me, I am an applied learner... and given a couple of the sources I've cited in my post, I don't quite get getting rid of this conditional logic yet. What is the best way to get rid of this smell? Thanks!

 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When the method name can be constructed from the parameter you use to distinguish them - as in your example code - one possibility is to use reflection.

Possibly your example code is just too much abstracted from your real code, though, and you can't apply that technique. In that case, can you show us your real code?
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you can use an enum type instead of your number you would have the possibility to use constant-specific method implementations.

An example from the book "Effective Java":


 
reply
    Bookmark Topic Watch Topic
  • New Topic