Jump to content

Software Design/Make if condition positive

From Wikiversity

Checklist questions:

  • Would arranging if-else branches so that the condition is positive (like if (cond) instead of if (!cond) make the code simpler?

All other things being equal with regard to the project's conventions about if-else branch arrangement, prefer

if (cond) {
  // do something
} else {
  // do something else
}

instead of

if (!cond) ...

If there is a negation, readers of the code have to mentally apply it every time they glance through the code. That is, eliminating a negation helps to reduce the cognitive load.

If the boolean variable used in the conditional expression already has negation embedded into it, for example, if the variable is called notDone, it might be better to convert it to a positive variable first to avoid both expression-level (i. e. using the negation operator) and semantic negation in the conditional expression.

Why not

[edit | edit source]

Depending on the project's conventions regarding if-else branch arrangement and specifics of the particular if-else block, there might be reasons to arrange branches in a certain way that are more important than keeping the conditional expression positive, for example, keeping the first branch shorter.[1] Other possibilities are listed here: Code organization conventions § Branch arrangement in if-else and switch statements.

A negative condition in an if branch may also allow early exit from the function and thus reducing the nesting of the bulk of the function.[2]

[edit | edit source]

References

[edit | edit source]
  1. Boswell, Dustin; Foucher, Trevor (2011). The Art of Readable Code. ISBN 978-0596802295.  Chapter 7, "The Order of if/else Blocks" section
  2. Atwood, Jeff (January 10, 2006). "Flattening Arrow Code".