You may find code that has an if-else conditional statement that is "in the negative" form. It is almost always easier to understand in the opposite way--in the positive.
BAD (but only a little):
if (foo != null)
{
// do NORMAL CASE stuff here
}
else
{
// do other stuff here
}
BETTER:
if (foo == null)
{
// do other stuff here
}
else
{
// do NORMAL CASE stuff here
}
Some would object that, “hey, the normal case stuff should come first”. That is author-centric coding, as if our code must follow our thinking when we wrote it. Instead, we need to have reader-centric coding—let’s make our code as easy as possible for others to understand what it does (and what it is supposed to do). The human mind can conceive of a “if-yes, else-no” pattern much more easily than “if-no, else not-no”.
Also, CONSIDER if you can short-circuit away the nesting with a control flow statement such as return, break, or throw.
if (foo == null)
{
// do other stuff here
return;
}
// do NORMAL CASE stuff here
Some advocate a single exit point as a rule, but I usually do not. One might think that using if-else is easier to read, but it isn’t—the cognitive load put on the reader by nesting and conditionals is worse than the ability to notice an early exit.
No comments:
Post a Comment