开发者

Boolean Logic question: can I coerce these 4 if statements into a single boolean statement?

I have a boolean logic question. I have the following if statements that should be able to be coalesced into a single boolean expression. Please help. I've spent way too much time on this and I'm actually 开发者_如何学JAVAtoo ashamed to ask my co-workers.

if (denyAll == true & allowOne == false) return false;
if (denyAll == true & allowOne == true) return true;
if (denyAll == false & allowOne == false) return false;
if (denyAll == false & allowOne == true) return true;
return true; //should never get here

I'm sure there is an elegant solution.

Thanks


Would return allowOne; do the trick?


I think it's just:

return allowOne;

The denyAll value doesn't seem to matter:

denyAll   allowOne   result
false     false      false
false     true       true
true      false      false
true      true       true


To supplement the other answers, some basic tips:

you can use if (allowOne) instead of if (allowOne == true) or if (!allowOne) instead of if (allowOne == false)

Also, with conditional operations, you should typically use the && operator instead of &, as this allows short-circuiting. For example in the expression if (denyAll && !allowOne), if denyAll is false, it will not bother evaluating !allowOne since the expression is already false.

Furthermore, if your method is returning a bool as it is here, then you can often simplify the expression into the return statement itself. For example this:

if (!denyAll && allowOne)
   return true;
else
   return false;

simplifies to this:

return (!denyAll && allowOne);


How about return allowOne;. If everything is just a variable and reading has no side effects, then that should have the same result.


It looks like the value that really matters is your "allowOne" bool (since it doesn't seem to matter what denyAlls value is). Assuming that, you van just check if allowOne is true.


Well as far as I can see:

If allowOne = true then return true;
return false;

would do it the "Deny all" setting doesnt seem to have any effect on the outcome and should not be there.


You could use something like this:

if (denyAll && !allowOne) 
    return false;
return denyAll || allowOne;

Nevertheless you should consider something that is more readable.

Update: As some others have pointed out (and what I haven't seen) is, that you actually ignore denyAll all, so return allowOne; is all you need.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜