Programming Search⌘K

Techniquecore

Consolidate conditional expression

Also called consolidate conditional, combine conditions, merge conditionals.

When several checks in a row give the same result, combine them into one condition with or and and, and extract it into a function whose name says the single rule that the checks make together.

Family
refactoring
Intent
Join checks with the same result into one named condition.

Purpose

Sometimes a function makes several checks in a row, and each one gives the same result. The checks look like separate rules, but they are one rule: if any of them is true, the answer is the same. Written apart, they hide that rule.

Consolidate conditional expression joins the checks into one condition, and then extracts the condition into a function. The catalogue card joins three checks that each return 0, on the seniority, the months of disability and the part-time status of an employee, into one function, isNotEligibleForDisability().1 The refactoring is in both editions of the book.23

Steps

  1. Make sure that none of the conditions has a side effect. If one has, first separate the query from the modifier.3
  2. Take two of the conditions and join them with a logical operator. Checks in a row that give the same result join with or. A check inside another check joins with and.3
  3. Test.
  4. Repeat until there is one condition.
  5. Extract the condition into a function with a name that says the rule. See Extract Function.

Example

A shop decides if an order can ship on the day it is placed. Three checks return false. After the refactoring, the three checks are one function, and the rule has a name.

import assert from "node:assert/strict";

function shipsTodayBefore(order, hour) {
  if (hour >= 15) return false;
  if (order.items.some((i) => i.backordered)) return false;
  if (order.address.country !== "NO") return false;
  return true;
}

function shipsToday(order, hour) {
  return !missesTodaysDispatch(order, hour);
}

function missesTodaysDispatch(order, hour) {
  return hour >= 15 || order.items.some((i) => i.backordered) || order.address.country !== "NO";
}

const items = [[], [{ backordered: false }], [{ backordered: false }, { backordered: true }]];
for (const hour of [9, 14, 15, 20]) for (const it of items) for (const country of ["NO", "SE"]) {
  const order = { items: it, address: { country } };
  assert.equal(shipsToday(order, hour), shipsTodayBefore(order, hour));
}
console.log("consolidate conditional expression: tests pass");
Output
consolidate conditional expression: tests pass

|| evaluates from left to right and stops at the first true operand, so the consolidated condition does the same checks, in the same order, as the three if statements.

Language What the example shows
JavaScript three checks in a row joined with or, as above
Python the same join with or, and a nested check joined with and
Go the same join with `
PythonGitHub
def ships_today_before(order: dict, hour: int) -> bool:
    if hour >= 15:
        return False
    if any(i["backordered"] for i in order["items"]):
        return False
    if order["country"] != "NO":
        return False
    return True


def misses_todays_dispatch(order: dict, hour: int) -> bool:
    return hour >= 15 or any(i["backordered"] for i in order["items"]) or order["country"] != "NO"


def ships_today(order: dict, hour: int) -> bool:
    return not misses_todays_dispatch(order, hour)


# A nested check with no else joins with `and`.
def gift_wrap_fee_before(order: dict) -> int:
    if order["gift"]:
        if order["country"] == "NO":
            return 30
    return 0


def gift_wrap_fee(order: dict) -> int:
    return 30 if order["gift"] and order["country"] == "NO" else 0


for hour in (9, 15):
    for items in ([], [{"backordered": True}]):
        for country in ("NO", "SE"):
            for gift in (False, True):
                o = {"items": items, "country": country, "gift": gift}
                assert ships_today(o, hour) == ships_today_before(o, hour)
                assert gift_wrap_fee(o) == gift_wrap_fee_before(o)
print("consolidate conditional expression: tests pass")
Output
consolidate conditional expression: tests pass
package main

import "fmt"

type Item struct{ Backordered bool }

type Order struct {
	Items   []Item
	Country string
}

func (o Order) hasBackorder() bool {
	for _, i := range o.Items {
		if i.Backordered {
			return true
		}
	}
	return false
}

func (o Order) shipsTodayBefore(hour int) bool {
	if hour >= 15 {
		return false
	}
	if o.hasBackorder() {
		return false
	}
	if o.Country != "NO" {
		return false
	}
	return true
}

func (o Order) missesTodaysDispatch(hour int) bool {
	return hour >= 15 || o.hasBackorder() || o.Country != "NO"
}

func (o Order) shipsToday(hour int) bool { return !o.missesTodaysDispatch(hour) }

func main() {
	for _, hour := range []int{9, 15} {
		for _, items := range [][]Item{nil, {{true}}} {
			for _, c := range []string{"NO", "SE"} {
				o := Order{items, c}
				if o.shipsToday(hour) != o.shipsTodayBefore(hour) {
					panic(fmt.Sprint("differs: ", o, hour))
				}
			}
		}
	}
	fmt.Println("consolidate conditional expression: tests pass")
}
Output
consolidate conditional expression: tests pass

When to use

  • Checks in a row with the same result. The case that the card shows.1
  • Nested ifs with no else. An if inside an if, where only the inner body does something, is one condition joined with and.3
  • Before Replace Nested Conditional with Guard Clauses. A function with fewer, named conditions is easier to turn into guard clauses. See Replace Nested Conditional with Guard Clauses.

Pitfalls

Checks that are separate rules. If the checks give the same result by chance, and can change for different reasons, they are not one rule. Keep them apart, so that a change to one does not change the others.

Side effects. A condition that changes state, or that writes to a log, runs in a different number of cases when it is joined with or and and, because of short-circuit evaluation. Take the side effect out first.3

Long conditions. A condition with many operators and negations is hard to read even when it has one name. Decompose it into named parts. See Decompose Conditional.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool.

References

  1. Martin Fowler, Catalog of Refactorings, Consolidate Conditional Expression, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 9, Simplifying Conditional Expressions, Consolidate Conditional Expression
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 10, Simplifying Conditional Logic, Consolidate Conditional Expression, motivation, mechanics and the examples with or and with and

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/BZ9C79/text.yaml