Yes.
Especially with names similar to your chosen names, i.e. CanDoSomething
and DoSomething
it is absolutely clear to any competent programmer what the second code does: “if and only if the condition holds, do something and return the result”. “if and only if” is the core meaning of the short-circuited &&
operator.
The first code is convoluted and unnecessarily long without giving any more information than the second code.
But in general, the two conditions may not form such an intimate relationship (as in CanDo
and Do
) and it might be better to separate them logically because putting them in the same conditional might not make intuitive sense.
A lot of people here claim that the first version is “much clearer”. I’d really like to hear their arguments. I can’t think of any.
On the other hand, there’s this closely related (although not quite the same) code:
if (condition)
return true;
else
return false;
this should always be transformed to this:
return condition;
No exception. It’s concise and still more readable to someone who is competent in the language.