Simplest way to write this logic

Viewed 136

I'm writing a functional that calls two nullable boolean APIs. If either API returns true, my function should return true. If both return false, my function should return false. Otherwise, my function should return null. In other words:

true, true -> true
true, false -> true
true, null -> true
false, false -> false
false, null -> null
null, null -> null

Is there a simple/elegant way to write this? Obviously an if-else chain like this would work, but I think it's fairly messy, especially since you have to account for that null is a falsy value.

if ($cond1 || $cond2) {
    return true;
} else ($cond1 === false && $cond2 === false) {
    return false;
} else {
    return null;
}
6 Answers

Stick to what you suggested. One point of improvement is that you don't need if - else branching since you're returning. You just need two ifs:

function evaluate(?bool $cond1, ?bool $cond2): ?bool
{
    if ($cond1 || $cond2) {
        return true;
    }
    if ($cond1 === false && $cond2 === false) {
        return false;
    }
    return null;
}

What about

return ($cond1 ? $cond1 : $cond2);

You can remove else if block like so:

if ($cond1 || $cond2) {
    return true;
}

return !isset($cond1, $cond2) ? null : false; 

You can simplify it down to:

return ($cond1 || $cond2) ? true : (!isset($cond1, $cond2) ? null : false)

But this gets hard to read and make sense of off.

what about :

if($cond1 === true || $cond2 === true){ 
 return true; 
}else{ //check first and sec cond for falsing
    if($cond1 === false && $cond2 === false){
      return false; 
    }else{ //else null it
      return null; 
    }
}

Given your stipulations (and assuming each argument is one of: null, true or false) you could shave a smidgeon:

function foo($a, $b) {
    if($a || $b)                    return true;
    if([$a, $b] === [false, false]) return false;
}

Below seems to be working, I have tried to logic using Javascript as illustrated below

  function testMyConditions($c1, $c2) {
      return ($c1 === true || $2 === true) ? true:  ($c1 === null || $c2 === null ? null: false)
    }

function testMyConditions($cond1, $cond2) {
  return ($cond1 === true || $cond2 === true) ? true:  ($cond1 === null || $cond2 === null ? null: false)
}

function runTests($cond1, $cond2, $expected) {
  console.log($cond1,  $cond2, $expected, $expected === testMyConditions($cond1, $cond2) ? '=> OK': '=> NOT OK')
}

runTests(true, true, true)
runTests(true, false, true)
runTests(true, null, true)
runTests(false, false, false)
runTests(false, null, null)
runTests(null, null, null)

Related