A flag argument is a boolean parameter whose only job is to pick which of two code paths a function runs. The caller passes true or false, and the function quietly becomes a different function.
The cost shows up at the call site. closeTicket(ticket, mailer, true) tells you nothing until you open the definition and find out what true means. Inside, the function carries two responsibilities joined by an if. Every change to one path risks the other, and tests have to cover both halves through one entry point.
In interviews this smell comes up in code review exercises and refactoring rounds. Interviewers want to see that you recognise the hidden second function and can name both behaviours clearly.
Signs
How to spot it in a review.
- A call site passes a bare literal like
trueorfalse, and you can't tell what it does without reading the function body. - The function body is one big
if (flag) { ... } else { ... }where the branches share little beyond a few setup lines. - Callers almost always pass a hard-coded literal, rarely a value computed at runtime.
- Parameter names like
isSpam,dryRun,silentorforcechange what the function does, not what data it works on. - Two or more booleans sit side by side, so the function really has four or more modes behind one name.
- Tests for the function are grouped by the flag value, with little overlap between the groups.
What it looks like
A typical case, in three languages.
type TicketStatus = "open" | "closed";
interface Ticket {
id: string;
subject: string;
requesterEmail: string;
status: TicketStatus;
tags: string[];
closedAt: Date | null;
}
interface Mailer {
send(to: string, subject: string, body: string): void;
}
// Before: the boolean picks which of two jobs runs.
function closeTicket(ticket: Ticket, mailer: Mailer, isSpam: boolean): void {
ticket.status = "closed";
ticket.closedAt = new Date();
if (isSpam) {
ticket.tags.push("spam");
} else {
mailer.send(
ticket.requesterEmail,
`Resolved: ${ticket.subject}`,
`Ticket ${ticket.id} is resolved. Reply to this email to reopen it.`
);
}
}
// Call sites read like riddles:
// closeTicket(ticket, mailer, true);
// closeTicket(ticket, mailer, false);
// After: one function per behaviour, shared steps extracted.
function markClosed(ticket: Ticket): void {
ticket.status = "closed";
ticket.closedAt = new Date();
}
function closeAsResolved(ticket: Ticket, mailer: Mailer): void {
markClosed(ticket);
mailer.send(
ticket.requesterEmail,
`Resolved: ${ticket.subject}`,
`Ticket ${ticket.id} is resolved. Reply to this email to reopen it.`
);
}
function closeAsSpam(ticket: Ticket): void {
markClosed(ticket);
ticket.tags.push("spam");
}from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional, Protocol
class Mailer(Protocol):
def send(self, to: str, subject: str, body: str) -> None: ...
@dataclass
class Ticket:
id: str
subject: str
requester_email: str
status: str = "open"
tags: list[str] = field(default_factory=list)
closed_at: Optional[datetime] = None
# Before: the boolean picks which of two jobs runs.
def close_ticket(ticket: Ticket, mailer: Mailer, is_spam: bool) -> None:
ticket.status = "closed"
ticket.closed_at = datetime.now(timezone.utc)
if is_spam:
ticket.tags.append("spam")
else:
mailer.send(
ticket.requester_email,
f"Resolved: {ticket.subject}",
f"Ticket {ticket.id} is resolved. Reply to this email to reopen it.",
)
# Call sites read like riddles:
# close_ticket(ticket, mailer, True)
# close_ticket(ticket, mailer, False)
# After: one function per behaviour, shared steps extracted.
def mark_closed(ticket: Ticket) -> None:
ticket.status = "closed"
ticket.closed_at = datetime.now(timezone.utc)
def close_as_resolved(ticket: Ticket, mailer: Mailer) -> None:
mark_closed(ticket)
mailer.send(
ticket.requester_email,
f"Resolved: {ticket.subject}",
f"Ticket {ticket.id} is resolved. Reply to this email to reopen it.",
)
def close_as_spam(ticket: Ticket) -> None:
mark_closed(ticket)
ticket.tags.append("spam")<?php
declare(strict_types=1);
interface Mailer
{
public function send(string $to, string $subject, string $body): void;
}
final class Ticket
{
public string $status = 'open';
/** @var string[] */
public array $tags = [];
public ?DateTimeImmutable $closedAt = null;
public function __construct(
public readonly string $id,
public readonly string $subject,
public readonly string $requesterEmail,
) {
}
}
// Before: the boolean picks which of two jobs runs.
function closeTicket(Ticket $ticket, Mailer $mailer, bool $isSpam): void
{
$ticket->status = 'closed';
$ticket->closedAt = new DateTimeImmutable();
if ($isSpam) {
$ticket->tags[] = 'spam';
} else {
$mailer->send(
$ticket->requesterEmail,
"Resolved: {$ticket->subject}",
"Ticket {$ticket->id} is resolved. Reply to this email to reopen it."
);
}
}
// Call sites read like riddles:
// closeTicket($ticket, $mailer, true);
// closeTicket($ticket, $mailer, false);
// After: one function per behaviour, shared steps extracted.
function markClosed(Ticket $ticket): void
{
$ticket->status = 'closed';
$ticket->closedAt = new DateTimeImmutable();
}
function closeAsResolved(Ticket $ticket, Mailer $mailer): void
{
markClosed($ticket);
$mailer->send(
$ticket->requesterEmail,
"Resolved: {$ticket->subject}",
"Ticket {$ticket->id} is resolved. Reply to this email to reopen it."
);
}
function closeAsSpam(Ticket $ticket): void
{
markClosed($ticket);
$ticket->tags[] = 'spam';
}In this helpdesk tool, agents close tickets either because the issue is fixed or because the ticket is junk. The isSpam flag forced the spam path to drag along a Mailer it never uses. After splitting, closeAsSpam no longer depends on the mailer at all, each call site states its intent, and the shared bookkeeping lives in markClosed, so it can't drift between the two paths.
Why it happens
How code ends up like this.
- A second use case appeared late, and adding a boolean was the smallest change that compiled.
- The two behaviours share a few setup lines, so duplicating them felt worse than branching.
- Someone wanted to keep the public API stable and avoided adding a new function name.
- Options were copied from a CLI or UI toggle straight into the domain layer without being translated into intent.
Treatment
The refactorings that cure it, and when to choose each.
- Remove Flag Argument: Replace a Boolean with Explicit Functions
Callers pass literal
trueorfalse. Create one explicitly named function per value, point each call site at the right one, then delete the flagged version. - Extract function: give a fragment a name
Both branches repeat the same setup or teardown. Pull the shared steps into a helper like
markClosedbefore or after splitting, so neither new function duplicates them. - Decompose Conditional: Name the Condition and Each Branch
The branches are long and tangled. Extract each branch body into a named function first, which makes the split mechanical.
- Replace Conditional with Polymorphism: One Class per Case
The same flag is checked in several functions across a class. That flag is really a type, so model the two behaviours as separate classes behind one interface.
- Introduce Parameter Object: Bundle Parameters That Travel Together
Several booleans travel together and the value really is data computed at runtime, such as user preferences. Group them into an options object with named fields.
- Change Function Declaration: Fix a Signature Without Breaking Callers
You can't split yet because of external callers. Rename the function and parameter so intent is clearer, and deprecate the flagged form while callers migrate.
Payoff
What you get once it's gone.
- Call sites state intent:
closeAsSpam(ticket)needs no comment. - Each function has one job, so it's easier to test, read and change.
- Dependencies shrink to what each path actually uses, like dropping the mailer from the spam path.
- Adding a third behaviour means adding a function, not nesting another
if.
When to leave it
Sometimes it's not worth fixing.
- The boolean is genuine data rather than a mode switch, as in
setVisible(isVisible)oruser.setNewsletterOptIn(checked), where the value comes straight from runtime state. - The flag is computed at runtime and passed through, so splitting would just move the same
ifinto every caller. - You're implementing a framework or library signature you don't control, such as an overridden method with a fixed boolean parameter.
- The language supports named arguments, the flag only tweaks a minor detail like
includeArchived, and the core behaviour stays the same.
Common questions
Short answers to the usual doubts.
Isn't a boolean parameter always a flag argument?
No. It's a flag argument when the value selects which logic runs and callers typically pass a literal. A boolean that's stored, forwarded or compared as data, like setEnabled(enabled) fed from a checkbox, is just a parameter. Ask whether you could name the two cases as two different verbs. If you can, it's probably a flag.
Do named arguments or keyword arguments fix the smell?
They fix the readability half. closeTicket(ticket, mailer, isSpam=True) is clearer at the call site. The function still does two jobs and still drags dependencies one path doesn't need. Named arguments are a reasonable stopgap, but splitting is the real fix when the branches differ substantially.
What about enums instead of booleans?
An enum like CloseReason.Spam reads better than true and leaves room for a third value. If the function still switches on it to run unrelated code, the smell is the same, just better labelled. Use the enum when the reason is data you store or report on, and split the behaviour when the branches do different work.
How do I handle a flag when there are dozens of external callers?
Add the two new functions first and have the old flagged function delegate to them. Mark the old one deprecated, migrate callers in small batches, then delete it. Each step keeps the build green and keeps every change small enough to review.
How should I talk about this in a code review interview?
Point at a call site with a bare true and say what you can't tell from it. Name the two behaviours the flag hides, propose a function for each, and mention the shared logic you'd extract. Then say when you'd leave it alone, for example when the value comes from user input. That last part shows judgement, not just pattern matching.