I have a logical situation that is best described as two “teams” trying to win a mission. The result of this task can be one winner, a draw (draw) or a winner (dead end).
I am currently using a nested if / else statement, for example:
// 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. } }
It seems rather spaghetti-like and repetitive. Is there a more logical, DRY template that I could use?
Another way would be if win (a) && win (b), then Draw, otherwise, if you win (a), otherwise, if you win (b).
Or:
if win(a) and win(b) then // Draw else if win(a) then // a wins else if win(b) then // b wins else // Stalemate
, , , .
switch:
switch (($team_a->win() << 1) + $team_b->win()) { case 3: // this is a draw case 2: // team_a is the winner case 1: // team_b is the winner case 0: // This is a stalemate, no winner. }
, , , . , $team_x->win() ($team_x->win() ? 1 : 0).
$team_x->win()
($team_x->win() ? 1 : 0)
if($TeamA->win() && $TeamB->win()){ // Tie }else if($TeamA->win()){ // Team A wins }else if($TeamB->win()){ // Team B wins }else{ // No winner }
, , win(), if...else, :
if...else
$team_a = $TeamA->win(); $team_b = $TeamB->win(); if($team_a && $team_b){ // Tie }else if($team_a){ // Team A wins }else if($team_b){ // Team B wins }else{ // No winner }
:
if($team_a->win() and $team_b->win()) { // Draw } elseif($team_a->win()) } // Team A Won } elseif($team_b->win()) } // Team B Won } else { // No Winner }
@Mark Byers, , .
$result_code = 0; if ($team_a->win()) $result_code += 1; if ($team_b->win()) $result_code += 2; switch ($result_code) { case 0: //stalemate case 1: //a wins case 2: //b wins case 3: //draw }
, , , , . * nix < 2 : , 4, 2 1 ..
, .
, , {} else :
function game_end($a,$b) { if ($team_a->win() && $team_b->win()) { // this is a draw return; } if ($team_a->win()) { // team_a is the winner return ; } if ($team_b->win()) { // team_b is the winner return ; } // This is a stalemate, no winner. }
...
-
IF(a AND b) THEN {a,b} ELSE If (a AND NOT(b)) THEN {a} ELSE If (not(a) AND NOT(b)) THEN { } ELSE {b}
, , .
, :
if (win(a) != win(b)) { // common code when there a winner, regardless of who if (win(a)) { // code specific to a winning } else { // code specific to b winning } } else { // common code for a non-result if (win(a)) { // code specific to a draw } else { // code specific to a stalemate } }
, , - , if/else if switch/case.
if/else if
switch/case
, , . (, e-):
if ($team_a->score() > $team_b->score()) return 'Team A wins!'; else if ($team_a->score() < $team_b->score()) return 'Team B wins!'; else return 'It a tie!';
( , )
DRY- , , /, , .
, , ... . 3 4 , , .
IF (A ^ B) -> draw ELSE (!A ^ !B) -> no win ELSE A -> a wins ELSE -> b wins
- . - $team_b->win() ( if).
$team_b->win()