Programming Search⌘K

Patterncore

Boolean parameter

Also called flag argument, boolean trap, boolean argument.

A code smell: a function takes a true or false argument that selects which of two things it does, so a call such as book(customer, false) does not say what it means.

Family
code-smell
Intent
Replace a boolean argument that picks the operation with a function for each operation, or with a named option, so that each call says what it does.
Also called
Flag Argument

Intent

Find the functions that take a boolean whose value chooses between two operations, such as book(customer, true) for a premium booking and book(customer, false) for a regular one. Give each operation its own function, or make the choice a named option, so that a reader of the call knows what it does without opening the function.

Problem

Martin Fowler defines the term on his bliki: "A flag argument is a kind of function argument that tells the function to carry out a different operation depending on its value."1 He writes that his general reaction to flag arguments is to avoid them, and he prefers separate methods, because "the separate methods communicate more clearly what my intention is when I make the call."1 He gives the example of a reader who sees book(martin, false) and must remember what false means, where regularBook(martin) says it.1

The forces are these:

  • The call site hides the meaning. A literal true or false has no name at the call. The reader must look up the parameter list, and a second boolean doubles the guessing.
  • The order is a trap. Two boolean parameters next to each other accept each other's values, and the compiler cannot tell.
  • The function does two things. The body tests the flag and runs one branch or the other, so it has two reasons to change, and its tests must cover both branches through one name.
  • Not every boolean is a flag. A boolean that is data, such as the value of a check box that the caller passes on, does not choose an operation. Fowler notes that an API "should be written to make it easier for the caller", and that a setter which takes a boolean from a UI control is better than a test of the value at each call.1

Solution

The refactoring is Remove Flag Argument, which the catalogue at refactoring.com also lists as Replace Parameter with Explicit Methods.2 The second edition of Refactoring describes it in the chapter on refactoring APIs.3

  1. Make a function for each value. Write premiumBook(customer) and regularBook(customer), each calling the old function with the literal value.
  2. Change the callers. Replace each call with a literal flag by the explicit function.
  3. Inline or hide the old function. If the two branches are separate, move each into its own function and delete the flag. If the branches are tangled, Fowler suggests keeping the flag function but hidden, as a private implementation with an ugly name that only the two explicit functions call.1

When the callers pass a variable, not a literal, the explicit functions do not help, because the caller would need an if to choose. Then the fix is a name at the call site: a keyword argument, an options object, or an enumeration in place of the boolean. Python can force the name; its tutorial explains that a * in the parameter list marks the parameters after it as keyword-only, so that they "must be passed by keyword argument".4

Fowler also notes the case where the flag can be derived: if the kind of booking depends only on the customer's status, the booking code should read the status itself, and the caller should not pass a flag at all.1

Example

A booking function takes a customer and a flag for premium seats. The calls read book(ada, true), and a reader must open the function to learn what true means.

import assert from "node:assert/strict";

// Before: a flag argument chooses the operation.
function bookBefore(customer, isPremium) {
  if (isPremium) return { customer, seat: "front", fee: 40 };
  return { customer, seat: "general", fee: 0 };
}

// After, the callers pass literals: a function for each operation.
const premiumBook = (customer) => ({ customer, seat: "front", fee: 40 });
const regularBook = (customer) => ({ customer, seat: "general", fee: 0 });

// After, the callers pass a value they read: a named option, not a bare boolean.
function book(customer, { tier }) {
  if (tier === "premium") return premiumBook(customer);
  if (tier === "regular") return regularBook(customer);
  throw new RangeError(`unknown tier ${tier}`);
}

assert.deepEqual(premiumBook("ada"), bookBefore("ada", true));
assert.deepEqual(regularBook("ada"), bookBefore("ada", false));
assert.deepEqual(book("ada", { tier: "premium" }), bookBefore("ada", true));
assert.throws(() => book("ada", { tier: "gold" }), RangeError);
// The flag accepts any value, and a truthy string silently books a premium seat.
assert.equal(bookBefore("ada", "no").fee, 40);
console.log("booking: tests pass");
Output
booking: tests pass

In the second version, each call says what it does: premiumBook(ada), or book(ada, { tier: "premium" }) when the tier comes from a form. A value that is not a tier fails at once, where the flag version took any truthy value as true.

Language What the example shows
JavaScript explicit functions and a named option, as above
Python explicit functions, and a keyword-only enumeration argument
Java explicit methods, and an enum in place of the boolean
Go explicit functions, and a named type with constants
PythonGitHub
from enum import Enum


# Before: a flag argument chooses the operation.
def book_before(customer, is_premium):
    if is_premium:
        return {"customer": customer, "seat": "front", "fee": 40}
    return {"customer": customer, "seat": "general", "fee": 0}


# After, the callers pass literals: a function for each operation.
def premium_book(customer):
    return {"customer": customer, "seat": "front", "fee": 40}


def regular_book(customer):
    return {"customer": customer, "seat": "general", "fee": 0}


# After, the callers pass a value they read: a keyword-only enumeration.
class Tier(Enum):
    PREMIUM = "premium"
    REGULAR = "regular"


def book(customer, *, tier):
    if tier is Tier.PREMIUM:
        return premium_book(customer)
    if tier is Tier.REGULAR:
        return regular_book(customer)
    raise ValueError(f"unknown tier {tier!r}")


assert premium_book("ada") == book_before("ada", True)
assert regular_book("ada") == book_before("ada", False)
assert book("ada", tier=Tier("premium")) == book_before("ada", True)
try:
    book("ada", Tier.PREMIUM)  # the * makes tier keyword-only
    raise AssertionError("a positional tier should be refused")
except TypeError:
    pass
try:
    Tier("gold")
    raise AssertionError("an unknown tier should be refused")
except ValueError:
    pass
assert book_before("ada", "no")["fee"] == 40  # any truthy value counts as True
print("booking: tests pass")
Output
booking: tests pass

The * in book(customer, *, tier) makes tier keyword-only, so each call must write tier=, and Tier("gold") fails when the value is read, not later inside the function.

JavaGitHub
public class Main {
    record Booking(String customer, String seat, int fee) {}

    // Before: a flag argument chooses the operation.
    static Booking bookBefore(String customer, boolean isPremium) {
        if (isPremium) {
            return new Booking(customer, "front", 40);
        }
        return new Booking(customer, "general", 0);
    }

    // After, the callers pass literals: a method for each operation.
    static Booking premiumBook(String customer) { return new Booking(customer, "front", 40); }
    static Booking regularBook(String customer) { return new Booking(customer, "general", 0); }

    // After, the callers pass a value they read: an enum in place of the boolean.
    enum Tier { PREMIUM, REGULAR }

    static Booking book(String customer, Tier tier) {
        return switch (tier) {
            case PREMIUM -> premiumBook(customer);
            case REGULAR -> regularBook(customer);
        };
    }

    public static void main(String[] args) {
        check(premiumBook("ada").equals(bookBefore("ada", true)), "premium");
        check(regularBook("ada").equals(bookBefore("ada", false)), "regular");
        check(book("ada", Tier.valueOf("PREMIUM")).equals(bookBefore("ada", true)), "tier");
        boolean refused = false;
        try {
            Tier.valueOf("GOLD");
        } catch (IllegalArgumentException e) {
            refused = true;
        }
        check(refused, "an unknown tier should be refused");
        System.out.println("booking: tests pass");
    }

    static void check(boolean ok, String what) {
        if (!ok) {
            throw new AssertionError(what);
        }
    }
}
Output
booking: tests pass

The switch over Tier has a case for each constant and no default, so if a third tier is added, the switch expression no longer compiles until it has a case for it.

package main

import "fmt"

type Booking struct {
	Customer, Seat string
	Fee            int
}

// Before: a flag argument chooses the operation.
func bookBefore(customer string, isPremium bool) Booking {
	if isPremium {
		return Booking{customer, "front", 40}
	}
	return Booking{customer, "general", 0}
}

// After, the callers pass literals: a function for each operation.
func PremiumBook(customer string) Booking { return Booking{customer, "front", 40} }
func RegularBook(customer string) Booking { return Booking{customer, "general", 0} }

// After, the callers pass a value they read: a named type with constants.
type Tier int

const (
	Regular Tier = iota + 1
	Premium
)

func ParseTier(s string) (Tier, error) {
	switch s {
	case "premium":
		return Premium, nil
	case "regular":
		return Regular, nil
	}
	return 0, fmt.Errorf("unknown tier %q", s)
}

func Book(customer string, tier Tier) Booking {
	if tier == Premium {
		return PremiumBook(customer)
	}
	return RegularBook(customer)
}

func main() {
	if PremiumBook("ada") != bookBefore("ada", true) || RegularBook("ada") != bookBefore("ada", false) {
		panic("explicit functions")
	}
	t, err := ParseTier("premium")
	if err != nil || Book("ada", t) != bookBefore("ada", true) {
		panic("tier")
	}
	if _, err := ParseTier("gold"); err == nil {
		panic("an unknown tier should be refused")
	}
	fmt.Println("booking: tests pass")
}
Output
booking: tests pass

A call Book("ada", Premium) names the choice, and the compiler refuses a bool where a Tier is expected.

Consequences

Each call reads as what it does, and each function does one thing. The tests name the operation that they cover.

The number of functions grows. Two flags give four combinations, and four explicit functions for them can be worse than one function with two named options. Remove the flag when the values pick operations that the callers think of as different; use a named option when the value is a setting that the callers pass through.

A hidden implementation that takes the flag keeps the tangled body in one place. That is a step, not an end: the branches still share a body, and a later change can separate them.

How to fix it

  • The callers pass a literal true or false: Remove Flag Argument, with one function for each value.2
  • The callers pass a value from data or a UI control: keep one function, and make the choice a named option or an enumeration.1
  • The flag can be derived from another argument: remove it, and let the function derive it.1
  • Several flags together: see Long Parameter List, and consider an options object or a parameter object.

Long Parameter List. Flags are often how a parameter list grows. See Long Parameter List.

Boolean type. The type itself, and why a value with two states says little about what the states mean. See Boolean type.

Repeated Switches. A flag that is tested in many functions is a switch on the same value in many places. See Repeated Switches.

References

  1. Martin Fowler, Flag Argument, bliki, 23 June 2011, the whole entry
  2. Martin Fowler, Catalog of Refactorings, the card Remove Flag Argument (alias Replace Parameter with Explicit Methods)
  3. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Remove Flag Argument
  4. The Python Tutorial, More Control Flow Tools, 4.9.3.3, Keyword-Only Arguments

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7T14G6/text.yaml