liveBook · Manning

Mutually exclusive condition

As explained in 100 Java Mistakes and How to Avoid Them

Mutually exclusive conditions are conditions that cannot be true simultaneously for the same program state.

Conditions are mutually exclusive when they cannot both be true for the same state. In an if–else chain, overlapping conditions make branch order significant: only the first matching branch runs. A condition dominates another when the second can be true only whenever the first is true. section 3.2

A dominated age condition

In getPlan, age >= 6 matches every age >= 18, so the later age >= 18 branch is unreachable and FULL is never returned. Put narrower conditions first or make ranges explicitly disjoint. section 3.2

Prevent dominance and overlapping-branch mistakes by:

  • Ordering specific tests before general tests, especially with instanceof checks and type hierarchies. section 3.2
  • Checking overlapping cases such as FizzBuzz divisibility and command-line prefixes before broader matches. section 3.2
  • Using explicit non-overlapping ranges or ordered switch pattern cases where supported. section 3.2
  • Reviewing static-analysis warnings, while recognizing that complex dominance may require understanding the type hierarchy and intended behavior. section 3.2
enum Plan {CHILD, FULL, FREE}
Plan getPlan(int age) {
  if (age >= 6) return Plan.CHILD;
  if (age >= 18) return Plan.FULL;    #1
  return Plan.FREE;
}

Inspect the unreachable FULL branch in the incorrectly ordered age test. section 3.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Analyzes numeric ranges, instanceof hierarchies, prefixes, FizzBuzz, and static-analysis limits.
Examples
Uses age tariffs, numeric conversion, FizzBuzz, command-line options, collection dispatch, and switch patterns.
What it assumes
Assumes familiarity with Java if–else statements, instanceof, collections, and basic static-analysis warnings.
What you can do after
Diagnose unreachable branches and reorder or rewrite conditions to preserve intended behavior.
How it connects
Connects conditional branching with instanceof checks, pattern matching, type hierarchies, and static analysis.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.