Java – refactoring multiple if else conditions in a method
I'm refactoring my existing code It actually works, but it's a bit confusing. Multiple if else conditions check the value of one variable and change the value of the second variable to the updated value obtained from the fixed enumeration structure
else if (var1 == 'valueX') { if (var2 == MyEnum.A) var2 = MyEnum.B; else if (var2 == MyEnum.B) var2 = MyEnum.C; else if (var2 == MyEnum.C) var2 = MyEnum.D; else if (var2 == MyEnum.D) var2 = MyEnum.A; } else if (....) { ..similar block of conditionals }
I'm a little confused about the best way to refactor and clean up this code Would you recommend using a switch? Or something more elegant?
Thank you in advance!
Solution
Using at least J2SE 1.5 forwarding, you can provide additional properties for enumeration This means that you can replace the entire if else string with something that looks like it
var2 = var1.getNextInSequence();
Now, in this case, it seems that you want this property to be a reference to another enumeration, which will add some wrinkles. For example, you can't forward reference enumerations when initializing them, but there may be a feasible solution
This works when the property is not another instance of the same enumeration:
public enum Animal { FOX(4),CHICKEN(2),WORM(0); private int countLegs; Animal(int n) { countLegs = n; } public int getLegCount() { return countLegs; } // .. more getters setters etc }
However, when enumerations are self - referential, you must be careful about the declaration order of your instances That is, there will be some problems:
public enum Animal { FOX(4,CHICKEN),// 'CHICKEN' doesn't exist yet WORM(0,null),CHICKEN(2,WORM); // this actually will compile private int countLegs; private Animal eatsWhat; Animal(int n,Animal dinner) { countLegs = n; eatsWhat = dinner; } public int getLegCount() { return countLegs; } // .. getters,setters,etc }
So if you need to use circular references between enumerations, you have to work on something else, but if not, you can use this technique, although you may have to order your enumeration instances to make them work