【问题标题】:Switch Statement inside condition refactoring条件重构中的 Switch 语句
【发布时间】:2018-05-18 16:19:14
【问题描述】:

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

【问题讨论】:

标签: java if-statement switch-statement conditional


【解决方案1】:

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

enum Direction {
    NORTH, EAST, SOUTH, WEST;

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

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多