The cleanest way to write a 2-boolean conditional (4 branches)

I have this code. true_varand other_true_varare values boolean. Four conditional branches are different.

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 “acceptable” way to write this? I could output all conditional expressions to methods that return a boolean, but that looks above.

+3
source share
4 answers

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

if (A)
{
  if (B) { // case 0 }
  else { // case 1 }
}
else
{
  if (B) { // something else }
  else { / crazy }
}
+2
source

That seems right.

It can go in any order, but yes, it seems like the right way to do it

0
source

, , . "" , .

, .

0

. , .

But none of us uses meaningless arbitrary variables, or at least none of us should. There is a reason that b and b result in the same code, and a &! B to another, etc. What does it mean for & b must be true? Name it. Same thing with the rest. Perhaps it turns out that some settings are related to behavior, and you can rewrite the code to reflect this.

We cannot answer the question as presented, due to the lack of meaning of the variables presented. When it makes sense, you can make a meaningful choice.

0
source

All Articles