在条件重构中切换语句

时间:2017-12-05 04:46:40

标签: java if-statement switch-statement conditional

我有一段可行的代码,但我不喜欢它看起来的样子。它看起来笨重而且凌乱。基本上是一个if语句,里面有一个switch语句。

有没有办法重构这个?也许知道如何处理它们?

private Direction update(Coordinates coordinate) {
    if (coordinate.isLeft()) {
        switch (coordinate.getDirection()) {
        case NORTH: return Direction.WEST;
        case SOUTH: return Direction.EASTH;
        case EASTH: return Direction.NORTH;
        case WEST: return Direction.SOUTH;
        }
    }
    if (coordinate.isRight()) {
        switch (coordinate.getDirection()) {
        case NORTH: return Direction.EASTH;
        case SOUTH: return Direction.WEST;
        case EASTH: return Direction.SOUTH;
        case WEST: return Direction.NORTH;
        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:2)

如果您顺时针订购枚举,您可以使用简单的索引从一个走到另一个:

enum Direction {
    NORTH, EAST, SOUTH, WEST;

    public Direction rotate(boolean clockwise) {
        int nextIndex = ordinal() + (clockwise ? 1 : 3);
        return values()[nextIndex % 4];
    }
}