Short-Circuit Boolean Evaluation

Some Boolean operations skip a later operand once the first result determines the answer.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Use a prerequisite first
  2. Check the effects you expect
  3. Put a necessary check before work that depends on it
  4. Choose whether later work should be skipped

Use a prerequisite first

In Python, denominator != 0 and total / denominator > 3 skips the division when the denominator is zero. Reversing the terms keeps the intended Boolean relation under ordinary algebra, but adds a failing execution path. Evaluation order is part of the rule.

Check the effects you expect

Combining a valid-file check and an operation that opens the file means only checked files are opened by that expression. If a caller needs to record every attempted path, use a separate auditing step. This exposes the side effects instead of tying them implicitly to truth evaluation.[1][2]

Put a necessary check before work that depends on it

The condition records > 0 and minutes / records > 4 evaluates the division only if Python first discovers a positive count. For zero, the first operand is false and the whole expression fails. At count five and minutes twenty-five, the division succeeds and the second comparison is true. Reversing the tests can evaluate an invalid operation before learning that it was unnecessary. Trace those two inputs in an evaluation order example.

Choose whether later work should be skipped

Consider a lookup that records every attempt as an effect. Placing it after a guard means that rejected inputs may never reach the lookup. That can be a useful performance choice when rejected work needs no record. If every input is meant to create an event, record the event at a deliberate boundary before checking any optional action. See return values and effects.

For a test, use a harmless function supplying a known result and counting its calls. Verify zero calls for a branch that must short-circuit, and one call for a branch that needs the result. This distinguishes equivalent final truth values with different operational behavior.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩