开发者

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

开发者 https://www.devze.com 2023-03-13 22:45 出处:网络
I\'ve got this code. true_var and other_true_var are boolean values. The four conditional branches are distinct.

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 so开发者_JAVA百科mething 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.


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 }
}


That seems about correct.

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


If some of the branch bodies are small I prefer to put them on top, this makes the code more readable. If there is a "natural" order for the conditionals follow that.

If you really care about speed you might want to put the most probable branch on the top.


The code as presented doesn't really tell us anything about the booleans and their semantics. Given two meaningless arbitrary independent booleans, the code as presented is fine.

But none of us uses meaningless arbitrary variables, or at least none of us should. There's a reason a&b leads to one code path, and a&!b to another, etc. What does it mean for a&b to be true? Name that. Same with the rest of them. Maybe it turns out that certain settings have related behavior, and you can rejigger the code to reflect that.

We can't really answer the question as presented, because of the lack of meaning of the variables presented. When there's meaning, you can make meaningful choices.

0

精彩评论

暂无评论...
验证码 换一张
取 消