De Morgan's Laws in Conditions

Distributing a negation across a compound test exchanges conjunction and disjunction while negating each operand.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Use a delivery rule
  2. Test asymmetric inputs
  3. Derive the failure rule from a successful case
  4. Preserve the prerequisite order when using the identity

Use a delivery rule

Suppose a package qualifies only if it is light and its contents are permitted. It fails if it is heavy or the contents are disallowed. For Boolean predicates, \(\neg(A\land B)=\neg A\lor\neg B\). The complementary expression can make a guard clause easier to read.

Test asymmetric inputs

Use cases with one valid criterion and one invalid one. Verifying only two valid and two invalid criteria may miss an accidental and in the failure condition. Observe whether expensive or effectful checks get skipped under short-circuit evaluation.[1][2]

Derive the failure rule from a successful case

Suppose an item is accepted when the label is supported and its quantity is positive. Successful cases satisfy both conditions. A failure occurs whenever the label is unsupported or the quantity is zero or below the permitted range under the stated input type. If you wrote the rejection using conjunction, an item failing only one check could pass. Test a supported label with zero and an unsupported label with a positive value. Using the truth table confirms both rows have the intended answer.

Preserve the prerequisite order when using the identity

Boolean identities describe truth values. Code can also raise exceptions or produce effects while evaluating operands. If a numerical comparison requires parsing to have succeeded, keep the parsing success check before the numerical one. A transformed expression should still skip any computation that lacks its prerequisite. Short-circuit behavior lets you check that order.

You can simplify a complex rule by naming its positive questions, such as known_label and in_quantity_range. Then write and test an explicit rejection rule. Include both failed and both successful as separate cases, and use independent examples so rewriting the expression cannot also change the test's expectation.

References

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