我想调用一个返回 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/