How does EK9 detect conditions that are always true or always false?
← Code Quality · Ref: Q735
EK9 tracks variable assignments through code paths and detects when a condition is guaranteed to produce the same result every time.
CONDITION ALWAYS TRUE (E08086)
If you assign a literal and then compare to the same value, the compiler knows the result. 'x <- 5; if x == 5' is always true. The else branch is dead code. Also detected when an outer condition implies an inner one: 'if count > 10; if count > 6' is always true since count > 10 implies count > 6.
CONDITION ALWAYS FALSE (E08087)
Similarly, 'x <- 5; if x == 10' is always false. The if body is dead code. Also detected for contradictory ranges: 'if count > 10 and count < 3' is always false.
WHEN TRACKING RESETS
The compiler stops tracking when a variable is reassigned from a function call or mutated by a non-pure call, since the value becomes unknown.
See Q557 for dead code detection overview. See Q558 for tautological conditions.
Example
defines module qa.codequality.conditiontruth defines function classifyScore() as pure -> score as Integer <- label as String: "average" highThreshold <- 90 lowThreshold <- 40 if score >= highThreshold label: "excellent" else if score < lowThreshold label: "poor" categorizeRange() as pure -> measurement as Integer <- category as String: "normal" upperBound <- 100 lowerBound <- 10 if measurement > upperBound category: "above" else if measurement < lowerBound category: "below" defines program ConditionTruthDemo() stdout <- Stdout() stdout.println(classifyScore(95)) stdout.println(classifyScore(30)) stdout.println(classifyScore(60)) stdout.println(categorizeRange(150)) stdout.println(categorizeRange(5)) stdout.println(categorizeRange(50))
Common mistakes
E50060 — String has no toUpperCase() method in EK9. Use upperCase() instead. See ek9 -h E50060 for details.
Incorrect:
stdout.println(classifyScore(95).toUpperCase())
Correct:
stdout.println(classifyScore(95))
E50060 — String has no toUpperCase() method in EK9. Use upperCase() instead. See ek9 -h E50060 for details.
Incorrect:
stdout.println(categorizeRange(150).toUpperCase())
Correct:
stdout.println(categorizeRange(150))
Other ways to ask this
- What is E08086 condition always true in EK9?
- What is E08087 condition always false in EK9?
- How does EK9 find dead code from constant conditions?
Coming from another language?
Java: SpotBugs detects some constant conditions. C/C++: compiler warnings for tautological comparisons with -Wtautological-compare. Rust: clippy detects some always-true conditions. Go: go vet detects some unreachable code. EK9: mandatory compiler error with full flow-sensitive tracking across branches.
Keywords: E08087, E08086, dead, always, true, code, false, condition, quality, tracking, flow, constant