Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to write 2-boolean conditional (4 branches)

Tags:

refactoring

I've got this code. true_var and other_true_var are boolean values. The four conditional branches are distinct.

if true_var && other_true_var:
    # do something 0
else if true_var && not other_true_var:
    # do something 1
else if not true_var && other_true_var:
    # do something else
else:
    # both are false, do a crazy thing

Is there an "accepted" way to write this? I could pull all the conditionals into methods which return a boolean, but that seems over the top.

like image 560
Kevin Burke Avatar asked Nov 19 '25 23:11

Kevin Burke


1 Answers

I would do it as follows for minimum number of tests:

if (A)
{
  if (B) { // case 0 }
  else { // case 1 }
}
else
{
  if (B) { // something else }
  else { / crazy }
}
like image 94
Steve Townsend Avatar answered Nov 21 '25 11:11

Steve Townsend