Suppose I have two methods bool Foo()
and bool Bar()
. Which of the following is more readable?
if(Foo())
{
SomeProperty = Bar();
}
else
{
SomeProperty = false;
}
or
SomeProperty = Foo() && Bar();
On the one hand, I consider the short-circuiting &&
to be a useful feature and the second code sample is much shorter. On the other hand, I'm not sure people are generally accustomed to seeing &&
outside a conditional statement, so I wonder if that would introduce some cognitive dissonance that makes the first sample the better option.
What do you think? Are there other factors that affect the decision? Like, if the &&
expression is longer than one line that can fit on the screen, should I prefer the former?
Post-answer clarifications:
A few things that I should have included in the initial question that the answers brought up.
Bar()
may be more expensive to execute thanFoo()
, but neither method should have side effects.- The methods are both named more appropriately, not like in this example.
Foo()
boils down to something likeCurrentUserAllowedToDoX()
andBar()
is more like,XCanBeDone()