Boolean Trap
An API design mistake where boolean parameters make function calls unreadable and easy to get wrong, because true and false say nothing about what they control.
Also known as: Flag Argument, Boolean Parameter Trap, Boolean Flag Parameters
Category: Software Development
Tags: software-design, software-development, api-design, programming, code-quality, anti-patterns
Explanation
Read this line: `window.resize(800, 600, true, false)`. What do `true` and `false` mean? Animate? Keep the aspect ratio? Center the window? You can't know without opening the documentation. And neither can the person reviewing the code.
That's the boolean trap. Ariya Hidayat gave it that name in his "Hall of API Shame" series in 2011. Martin Fowler describes the same problem as "flag arguments", and Robert C. Martin's Clean Code recommends avoiding them altogether.
**Why it's a trap**:
- **Unreadable call sites**: `true` carries no meaning on its own
- **Easy to swap**: With two booleans next to each other, putting them in the wrong order compiles fine
- **Hidden double behavior**: A boolean flag often means the function does two different things, and should really be two functions
- **Hard to extend**: The day you need a third option, a boolean can't represent it
**Examples of the trap and the fix**:
- `setVisible(false)` reads fine, but nobody can tell whether `false` in `widget.repaint(false)` means "don't erase the background" or "don't wait"
- `render(true)` → `renderPreview()` and `renderFinal()`
- `copy(src, dst, true)` → `copy(src, dst, { overwrite: true })`
- `createSlider(true)` → `createSlider(Orientation.Horizontal)`
**How to avoid it**:
1. **Split the function** when the boolean selects between two behaviors
2. **Use an enum** for named choices (there might be more than two one day)
3. **Use named parameters or an options object** if your language supports them
4. **Lean on your editor's parameter hints**, but don't rely on them: code is also read in diffs, logs and reviews
The boolean trap is a small, everyday example of the Hard to Misuse principle. An interface should make the correct call obvious from reading it.
Related Concepts
← Back to all concepts