DEV Community

Sualeh Fatehi
Sualeh Fatehi

Posted on

3-way Boolean Anti-pattern

In Java, the "3-way Boolean" anti-pattern is what you get when you use the boxed type Boolean (instead of primitive boolean) and you implicitly allow it to represent three states:

  • true
  • false
  • null ← the third, often accidental, state

That "third state" becomes a trap because most code reads like it's dealing with a simple yes/ no flag, but at runtime it can behave differently (or crash) when the value is null.

Why it's an anti-pattern

  • It creates implicit tri-state logic without making it explicit
    A variable named enabled, isReady, shouldRetry, etc. strongly implies binary logic, but Boolean quietly allows null, which means unknown, not set, not loaded, not applicable, or sometimes just "bug".

  • It can throw NullPointerException (NPE) during unboxing
    Common expressions like these will NPE if the Boolean is null:

   Boolean flag = getFlag();     // could be null
   if (flag) {                   // auto-unboxing -> NPE if null
       // ...
   }
Enter fullscreen mode Exit fullscreen mode

This exact failure mode is commonly seen during upgrades or refactors because the code compiles fine but fails at runtime.

  • It leads to confusing "null means false... except when it doesn't" logic People often "fix" the NullPointerException by doing inconsistent checks:
   if (flag != null && flag) ...
   // elsewhere
   if (Boolean.TRUE.equals(flag)) ...
   // elsewhere
   if (Boolean.FALSE.equals(flag)) ...
Enter fullscreen mode Exit fullscreen mode

Now your codebase has multiple semantic interpretations of null.

Top comments (0)