This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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)
else if (i = 2)
else if (i = 3)
else (i = 4)
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:
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!
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?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus