问题描述
我正在重构我现有的代码.它实际上工作正常,但它有点混乱,有多个 if-else 条件检查一个变量的值并将第二个变量的值更改为从固定枚举结构中获取的更新值.
i am in the process of refactoring my existing code. it actually works fine, but it is a bit cluttered with multiple if-else conditionals checking the value of one variable and change the value of a second variable to an updated value taken from a 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 am a bit confused as to what is the best way to refactor and clean-up this code. would you suggest the use of a switch perhaps? or something more elegant?
提前致谢!
推荐答案
至少在 j2se 1.5 之前,你可以给枚举额外的属性.这意味着您可以将整个 if-else 字符串替换为类似
at least with j2se 1.5 forward, you can give enums extra attributes. this means you might be able to replace that entire string of if-else with something that looks like
var2 = var1.getnextinsequence();
现在,在这种情况下,您似乎希望该属性是对另一个枚举的引用,这会增加一些麻烦,例如,当您初始化它们时您不能转发引用枚举,但可能有一个可行的以这种方式为您提供百家乐凯发k8的解决方案.
now, in this case, it looks like you would want the attribute to be a reference to another enum, which adds some wrinkles, for example you can't forward reference enums when you initialize them, but there might be a workable solution for you this way.
当属性不是同一个枚举的其他实例时,这种事情会起作用:
when the attributes aren't other instances of the same enum, this kind of thing will work:
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 }
但是当枚举是自引用的时,你必须注意你的实例的声明顺序.即,这会有一些问题:
but when the enum is self-referential, you have to be careful about the order of declaration of your instances. i.e., this will have some issues:
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 had need of a circular set of references among the enums, you'd have to work something else out, but if not, you could use this technique, though you may have to order your enum instances just so to make it work.