Java - 更适合我的控制流的习惯用法

标签 java

我想调用一个返回 false 或整数的方法。目前我的代码是:

int winningID = -1;
if((ID = isThereAWinner()) != -1) {
    // use the winner's ID
} else {
    // there's no winner, do something else
}

private int isThereAWinner() {
    // if a winner is found
    return winnersID;
    // else
    return -1;
}

我不喜欢 if((ID = isThereAWinner()) != -1) 位,因为它读起来不太好,但与 C 不同,您不能将 boolean 值表示为Java中的整数。有更好的方法吗?

最佳答案

我会使用类似于 Mat 的回答:

class Result {
    public static Result withWinner(int winner) {
        return new Result(winner);
    }

    public static Result withoutWinner() {
        return new Result(NO_WINNER);
    }

    private static final int NO_WINNER = -1;

    private int winnerId;

    private Result(int id) {
        winnerId = id;
    }

    private int getWinnerId() {
        return winnerId;
    }

    private boolean hasWinner() {
        return winnerId != NO_WINNER;
    }
}

此类隐藏了如果根本没有赢家,您实际如何表示的实现细节。

然后在您的获胜者查找方法中:

private Result isThereAWinner() {
    // if a winner is found
    return Result.withWinner(winnersID);
    // else
    return Result.withoutWinner();
}

在你的调用方法中:

Result result = isThereAWinner();
if(result.hasWinner()) {
    int id = result.getWinnerId();
} else {
    // do something else
}

这可能看起来有点过于复杂,但如果将来有其他结果选项,这种方法会更加灵活。

关于Java - 更适合我的控制流的习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9128442/

相关文章:

java - 通过构造函数将变量从子类添加到父类(super class)

java - 修改 keystore 文件中别名的组织

java - 如何从 Maven 依赖项构建 java 9 依赖项

java - 如何判断我的 JComponent 是否正在接收来自软件的重绘调用?

java - 为什么 javax.xml.xpath.XPath 对克隆节点的行为不同?

java - 当返回 404 的 HttpStatus 代码时,如何区分托管资源(在 url 上)的服务器是否已关闭或资源是否不存在

java - System.out .write() 执行但不打印

java - 使用jsoup对Html字符进行编码

java - 通过 jConsole/JMX 的 Activemq Artemis

java - OOP 文件读取问题