Skip to the workspace
Pebellslearn by building
Clean Code Principles  ›  Capstone Project

Avoid Passing Nulls and Booleans

Avoid passing nulls, booleans 14 minFlag arguments hide two functions inside one and null arguments hide a missing case, so both are better replaced by separate functions, named options or real objects.

software design architecture / Avoid Passing Nulls and Booleans

Explore each scene at your own pace.

01 · The rule

The rule

Avoid Passing Nulls and Booleans

In a Shelfwise pull request you find print_invoice(order, True, None). What does True do? What happens because of None? You cannot tell without opening the function, and neither can the next reader. A call should explain itself, and bare flags and nulls make that impossible.

The rule

A flag argument hides two functions; a null argument hides a missing case.

Boolean flags. A function that takes True or False to switch its behaviour is really two functions sharing one name:

def print_invoice(order, duplicate):
    if duplicate:
        ...  # stamp "COPY", skip the payment QR code
    else:
        ...  # normal invoice

Every caller must remember what the boolean means, and the body carries both behaviours. Better options:

  • Split it: print_invoice(order) and print_duplicate_invoice(order).
  • Name it at the call, when the flag really is a small option: print_invoice(order, duplicate=True). Python's keyword-only parameters (declared after a *) can enforce this.

Nulls. Passing None to mean "use the default" or "not applicable" forces the function to check for it, and returning None for "not found" forces every caller to check too. Forget once, and the program crashes somewhere far from the real cause with a message like 'NoneType' object has no attribute 'email'. Better options:

  • Make the argument required and pass the real value.
  • Give it a sensible default in the signature.
  • For "not found", raise a clear exception, or offer a separate question such as customer_exists(email).

When None really is a normal answer, at least make it visible. A type hint such as def find_customer(email) -> Customer | None tells every reader, and tools like type checkers, that a check is required before use.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.