条件重构中的 Switch 语句

Switch Statement inside condition refactoring

我有一段代码可以工作,但我不喜欢它的样子。它看起来笨重而凌乱。基本上是一个 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;
}

如果您按顺时针顺序排列枚举,则可以使用简单的索引从一个走到下一个:

enum Direction {
    NORTH, EAST, SOUTH, WEST;

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