Techniquecore
Decompose conditional
Also called decompose conditional, extract condition.
When an if statement has a long condition and long branches, extract the condition and each branch into a function with a name that says what it means, so that the if statement reads as the rule.
- Family
- refactoring
- Intent
- Name the condition and each branch of a complex conditional.
Purpose
A conditional with a long condition and long branches says how the code decides, but not why. A reader sees two date comparisons and two formulas, and must work out that the code charges a summer rate in summer.
Decompose conditional is Extract Function applied to the parts of a conditional. The condition becomes a function, and each branch becomes a function. The catalogue card turns a test of a date against the start and end of summer into summer(), and the two formulas into summerCharge() and regularCharge().1 The refactoring is in both editions of the book.23
Steps
- Extract the condition into a function whose name says what the condition means.3
- Extract the then branch into a function.
- Extract each else branch into a function.
- Test after each extraction.
- If the result is an if statement whose branches only assign one variable, consider a conditional expression, such as the ternary operator.
Example
A library charges a late fee. The fee is lower for a member under 18 and is not charged in the grace period. After the refactoring, the if statement says the rule, and each function says one part of it.
import assert from "node:assert/strict";
function lateFeeBefore(loan, now) {
const daysLate = Math.floor((now - loan.due) / 86400000);
let fee;
if (daysLate > 3 && !(loan.member.age < 18 || loan.member.tier === "staff")) {
fee = Math.min(daysLate * 25, loan.item.priceCents);
} else {
fee = daysLate > 3 ? Math.min(daysLate * 10, 500) : 0;
}
return fee;
}
const DAY_MS = 86400000;
const GRACE_DAYS = 3;
function lateFee(loan, now) {
const daysLate = Math.floor((now - loan.due) / DAY_MS);
if (daysLate <= GRACE_DAYS) return 0;
return paysFullFee(loan.member) ? fullFee(daysLate, loan.item) : reducedFee(daysLate);
}
function paysFullFee(member) {
return !(member.age < 18 || member.tier === "staff");
}
function fullFee(daysLate, item) {
return Math.min(daysLate * 25, item.priceCents);
}
function reducedFee(daysLate) {
return Math.min(daysLate * 10, 500);
}
const due = Date.UTC(2026, 0, 1);
const item = { priceCents: 1999 };
for (const age of [12, 40]) for (const tier of ["staff", "public"]) for (const d of [0, 3, 4, 30, 200]) {
const loan = { due, item, member: { age, tier } };
assert.equal(lateFee(loan, due + d * DAY_MS), lateFeeBefore(loan, due + d * DAY_MS));
}
console.log("decompose conditional: tests pass");
decompose conditional: tests pass
The test runs the two versions for each kind of member and for days in and after the grace period. The step that took the grace period out of the condition is a guard clause; see Replace Nested Conditional with Guard Clauses.
| Language | What the example shows |
|---|---|
| JavaScript | the condition and the two branches as functions, as above |
| Python | the same decomposition with a dataclass for the loan |
| Go | the same decomposition with methods on the member type |
from dataclasses import dataclass
DAY_SECONDS = 86400
GRACE_DAYS = 3
@dataclass(frozen=True)
class Member:
age: int
tier: str
@dataclass(frozen=True)
class Loan:
due: int # seconds since the epoch
price_cents: int
member: Member
def late_fee_before(loan: Loan, now: int) -> int:
days_late = (now - loan.due) // DAY_SECONDS
if days_late > 3 and not (loan.member.age < 18 or loan.member.tier == "staff"):
fee = min(days_late * 25, loan.price_cents)
else:
fee = min(days_late * 10, 500) if days_late > 3 else 0
return fee
def late_fee(loan: Loan, now: int) -> int:
days_late = (now - loan.due) // DAY_SECONDS
if days_late <= GRACE_DAYS:
return 0
if pays_full_fee(loan.member):
return full_fee(days_late, loan.price_cents)
return reduced_fee(days_late)
def pays_full_fee(member: Member) -> bool:
return not (member.age < 18 or member.tier == "staff")
def full_fee(days_late: int, price_cents: int) -> int:
return min(days_late * 25, price_cents)
def reduced_fee(days_late: int) -> int:
return min(days_late * 10, 500)
for age in (12, 40):
for tier in ("staff", "public"):
loan = Loan(due=0, price_cents=1999, member=Member(age, tier))
for d in (0, 3, 4, 30, 200):
assert late_fee(loan, d * DAY_SECONDS) == late_fee_before(loan, d * DAY_SECONDS)
print("decompose conditional: tests pass")
decompose conditional: tests pass
package main
import "fmt"
const graceDays = 3
type Member struct {
Age int
Tier string
}
// PaysFullFee is the condition, with a name that says the rule.
func (m Member) PaysFullFee() bool {
return !(m.Age < 18 || m.Tier == "staff")
}
func lateFeeBefore(daysLate, priceCents int, m Member) int {
var fee int
if daysLate > 3 && !(m.Age < 18 || m.Tier == "staff") {
fee = min(daysLate*25, priceCents)
} else if daysLate > 3 {
fee = min(daysLate*10, 500)
}
return fee
}
func lateFee(daysLate, priceCents int, m Member) int {
if daysLate <= graceDays {
return 0
}
if m.PaysFullFee() {
return fullFee(daysLate, priceCents)
}
return reducedFee(daysLate)
}
func fullFee(daysLate, priceCents int) int { return min(daysLate*25, priceCents) }
func reducedFee(daysLate int) int { return min(daysLate*10, 500) }
func main() {
for _, age := range []int{12, 40} {
for _, tier := range []string{"staff", "public"} {
for _, d := range []int{0, 3, 4, 30, 200} {
m := Member{age, tier}
if lateFee(d, 1999, m) != lateFeeBefore(d, 1999, m) {
panic(fmt.Sprint("differs: ", m, d))
}
}
}
}
fmt.Println("decompose conditional: tests pass")
}
decompose conditional: tests pass
When to use
- A condition that needs a comment. If a reader needs a comment to know what a condition tests, the comment is the name of a function.
- Branches that do different things at length. A branch of many lines is a function with no name.
- A long function. A long conditional is a frequent part of a long function.
Pitfalls
Names that repeat the code. A function named isAgeUnder18OrStaff says no more than the expression. Name the rule: paysFullFee.
Changed evaluation. An extracted condition is still evaluated once, in the same place. If a part of the condition has a side effect, or is expensive, keep the order and the number of calls the same.
Too many small functions. For a condition that is already clear, a function adds a name to look up. Decompose a conditional when the parts have a meaning that the code does not show.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. Each step is an Extract Function, and editors that can extract a function can do each step.
References
- Martin Fowler, Catalog of Refactorings, Decompose Conditional, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 9, Simplifying Conditional Expressions, Decompose Conditional
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 10, Simplifying Conditional Logic, Decompose Conditional, motivation and mechanics
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XXKNP7 Edit this page History Report an error Markdown