在方法中重构多个 if-else 条件

2022-01-20 00:00:00 refactoring conditional java

我正在重构我现有的代码.它实际上工作正常,但它有点混乱,有多个 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();

现在,在这种情况下,您似乎希望该属性是对另一个枚举的引用,这会增加一些麻烦,例如,当您初始化它们时您不能转发引用枚举,但可能有一个可行的以这种方式为您提供解决方案.

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.

相关文章