Flag Arguments
Boolean arguments that change function behavior.
“Boolean arguments that declare the function does two different things.” – Robert C. Martin
Signs of Use (Symptoms)
-
function render(data, isAdmin: boolean). -
function process(order, dryRun: boolean).
Why it is bad (Consequences)
- SRP: The function does two things depending on the flag.
- Readability:
render(data, true)- true for what?
Why it happens (Root Cause)
Adding a boolean is faster than creating a new function.
When it might be okay (Exceptions)
- Very common, obvious flags (e.g.,
verbose: booleanfor logging).
Explanation
Problem
save(user, isNew). If isNew is true, insert. If false, update.
The Flaw
The function does two distinct things. Split it.
Real world analogy
A button that says “Press for A or hold for B”. Just have two buttons.
Refactoring Solution
- Remove Flag Argument: Create two separate functions:
createUser(),updateUser().
Pros and Cons (of the Antipattern)
| Pros (Why people do it) | Cons (The price you pay) |
|---|---|
Comparison
- Related Antipatterns: Long Method.
- Related Principles: SRP.
Code example
Typescript
Bad (The Antipattern)
Good (The Fix)