Ste*_*hen 5 php language-agnostic boolean-logic nested-if
我有一个逻辑情况,最好描述为试图赢得任务的两个"团队".这项任务的结果可能是一个单一的胜利者,一个平局(平局),或者没有胜利者(僵局).
目前,我正在使用嵌套的if/else语句,如下所示:
// using PHP, but the concept seems language agnostic.
if ($team_a->win()) {
if ($team_b->win()) {
// this is a draw
} else {
// team_a is the winner
}
} else {
if ($team_b->win()) {
// team_b is the winner
} else {
// This is a stalemate, no winner.
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎很像意大利面和重复.我可以使用更合乎逻辑的DRY模式吗?
另一种方法是如果赢(a)&&赢(b)然后抽奖,否则如果赢(a),否则如果赢(b).
要么:
if win(a) and win(b) then
// Draw
else if win(a) then
// a wins
else if win(b) then
// b wins
else
// Stalemate
Run Code Online (Sandbox Code Playgroud)