Decompose Conditional is a small refactoring with a large effect on readability. You take an if statement whose condition is a pile of boolean operators and whose branches are blocks of arithmetic. You extract the condition into a function that names the business rule, and you extract each branch into a function that names what happens. The top-level code then reads like the policy it implements.
Interviewers often hand you a function like this in a refactoring or code-review round. They want to see you spot it quickly, keep behaviour identical, and work in small steps with tests behind you.
The problem
A situation where the obvious design starts to hurt.
Picture Helpdeck, a support tool used by a SaaS company with free, team and enterprise plans. Its routeTicket function decides where a new ticket goes. Severe enterprise tickets opened outside office hours (Monday to Friday, 08:00 to 18:00) page the on-call engineer. Everything else lands in a queue with an SLA derived from the plan and severity.
All of that sits in one if with a four-clause condition and two branches of inline numbers. A comment above it explains what the condition means, which is a sign the code cannot explain itself. When the support lead asks to move office hours to 07:00 or to treat severity 2 as an incident, you have to parse the whole expression to find the right clause.
Before and after
The same code, before and after the change.
Before
type Plan = "free" | "team" | "enterprise";
interface Ticket {
id: string;
plan: Plan;
severity: number; // 1 = low, 4 = critical
}
interface Route {
queue: string;
slaMinutes: number;
pageOnCall: boolean;
}
// dayOfWeek: 0 = Sunday ... 6 = Saturday
export function routeTicket(ticket: Ticket, hour: number, dayOfWeek: number): Route {
// Severe enterprise tickets opened outside office hours
// (Mon-Fri, 08:00-18:00) page the on-call engineer.
if (
ticket.plan === "enterprise" &&
ticket.severity >= 3 &&
(hour < 8 || hour >= 18 || dayOfWeek === 0 || dayOfWeek === 6)
) {
const sla = ticket.severity === 4 ? 15 : 30;
return { queue: "on-call", slaMinutes: sla, pageOnCall: true };
} else {
const base = ticket.plan === "free" ? 2880 : 480;
const queue = ticket.plan === "free" ? "community" : "standard";
return { queue, slaMinutes: Math.floor(base / ticket.severity), pageOnCall: false };
}
}from dataclasses import dataclass
from typing import Literal
Plan = Literal["free", "team", "enterprise"]
@dataclass(frozen=True)
class Ticket:
id: str
plan: Plan
severity: int # 1 = low, 4 = critical
@dataclass(frozen=True)
class Route:
queue: str
sla_minutes: int
page_on_call: bool
# day_of_week: 0 = Sunday ... 6 = Saturday
def route_ticket(ticket: Ticket, hour: int, day_of_week: int) -> Route:
# Severe enterprise tickets opened outside office hours
# (Mon-Fri, 08:00-18:00) page the on-call engineer.
if (
ticket.plan == "enterprise"
and ticket.severity >= 3
and (hour < 8 or hour >= 18 or day_of_week == 0 or day_of_week == 6)
):
sla = 15 if ticket.severity == 4 else 30
return Route("on-call", sla, True)
else:
base = 2880 if ticket.plan == "free" else 480
queue = "community" if ticket.plan == "free" else "standard"
return Route(queue, base // ticket.severity, False)<?php
declare(strict_types=1);
final class Ticket
{
public function __construct(
public readonly string $id,
public readonly string $plan, // free, team or enterprise
public readonly int $severity, // 1 = low, 4 = critical
) {}
}
final class Route
{
public function __construct(
public readonly string $queue,
public readonly int $slaMinutes,
public readonly bool $pageOnCall,
) {}
}
// $dayOfWeek: 0 = Sunday ... 6 = Saturday
function routeTicket(Ticket $ticket, int $hour, int $dayOfWeek): Route
{
// Severe enterprise tickets opened outside office hours
// (Mon-Fri, 08:00-18:00) page the on-call engineer.
if (
$ticket->plan === 'enterprise'
&& $ticket->severity >= 3
&& ($hour < 8 || $hour >= 18 || $dayOfWeek === 0 || $dayOfWeek === 6)
) {
$sla = $ticket->severity === 4 ? 15 : 30;
return new Route('on-call', $sla, true);
} else {
$base = $ticket->plan === 'free' ? 2880 : 480;
$queue = $ticket->plan === 'free' ? 'community' : 'standard';
return new Route($queue, intdiv($base, $ticket->severity), false);
}
}After
type Plan = "free" | "team" | "enterprise";
interface Ticket {
id: string;
plan: Plan;
severity: number; // 1 = low, 4 = critical
}
interface Route {
queue: string;
slaMinutes: number;
pageOnCall: boolean;
}
const OFFICE_OPENS = 8;
const OFFICE_CLOSES = 18;
// dayOfWeek: 0 = Sunday ... 6 = Saturday
export function routeTicket(ticket: Ticket, hour: number, dayOfWeek: number): Route {
if (needsOnCallPage(ticket, hour, dayOfWeek)) {
return onCallRoute(ticket);
}
return queuedRoute(ticket);
}
function needsOnCallPage(ticket: Ticket, hour: number, dayOfWeek: number): boolean {
return isEnterpriseIncident(ticket) && isOutsideOfficeHours(hour, dayOfWeek);
}
function isEnterpriseIncident(ticket: Ticket): boolean {
return ticket.plan === "enterprise" && ticket.severity >= 3;
}
function isOutsideOfficeHours(hour: number, dayOfWeek: number): boolean {
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
return hour < OFFICE_OPENS || hour >= OFFICE_CLOSES || isWeekend;
}
function onCallRoute(ticket: Ticket): Route {
const slaMinutes = ticket.severity === 4 ? 15 : 30;
return { queue: "on-call", slaMinutes, pageOnCall: true };
}
function queuedRoute(ticket: Ticket): Route {
const isFree = ticket.plan === "free";
const baseMinutes = isFree ? 2880 : 480;
return {
queue: isFree ? "community" : "standard",
slaMinutes: Math.floor(baseMinutes / ticket.severity),
pageOnCall: false,
};
}from dataclasses import dataclass
from typing import Literal
Plan = Literal["free", "team", "enterprise"]
OFFICE_OPENS = 8
OFFICE_CLOSES = 18
@dataclass(frozen=True)
class Ticket:
id: str
plan: Plan
severity: int # 1 = low, 4 = critical
@dataclass(frozen=True)
class Route:
queue: str
sla_minutes: int
page_on_call: bool
# day_of_week: 0 = Sunday ... 6 = Saturday
def route_ticket(ticket: Ticket, hour: int, day_of_week: int) -> Route:
if _needs_on_call_page(ticket, hour, day_of_week):
return _on_call_route(ticket)
return _queued_route(ticket)
def _needs_on_call_page(ticket: Ticket, hour: int, day_of_week: int) -> bool:
return _is_enterprise_incident(ticket) and _is_outside_office_hours(hour, day_of_week)
def _is_enterprise_incident(ticket: Ticket) -> bool:
return ticket.plan == "enterprise" and ticket.severity >= 3
def _is_outside_office_hours(hour: int, day_of_week: int) -> bool:
is_weekend = day_of_week in (0, 6)
return hour < OFFICE_OPENS or hour >= OFFICE_CLOSES or is_weekend
def _on_call_route(ticket: Ticket) -> Route:
sla_minutes = 15 if ticket.severity == 4 else 30
return Route("on-call", sla_minutes, True)
def _queued_route(ticket: Ticket) -> Route:
is_free = ticket.plan == "free"
base_minutes = 2880 if is_free else 480
queue = "community" if is_free else "standard"
return Route(queue, base_minutes // ticket.severity, False)<?php
declare(strict_types=1);
const OFFICE_OPENS = 8;
const OFFICE_CLOSES = 18;
final class Ticket
{
public function __construct(
public readonly string $id,
public readonly string $plan, // free, team or enterprise
public readonly int $severity, // 1 = low, 4 = critical
) {}
}
final class Route
{
public function __construct(
public readonly string $queue,
public readonly int $slaMinutes,
public readonly bool $pageOnCall,
) {}
}
// $dayOfWeek: 0 = Sunday ... 6 = Saturday
function routeTicket(Ticket $ticket, int $hour, int $dayOfWeek): Route
{
if (needsOnCallPage($ticket, $hour, $dayOfWeek)) {
return onCallRoute($ticket);
}
return queuedRoute($ticket);
}
function needsOnCallPage(Ticket $ticket, int $hour, int $dayOfWeek): bool
{
return isEnterpriseIncident($ticket) && isOutsideOfficeHours($hour, $dayOfWeek);
}
function isEnterpriseIncident(Ticket $ticket): bool
{
return $ticket->plan === 'enterprise' && $ticket->severity >= 3;
}
function isOutsideOfficeHours(int $hour, int $dayOfWeek): bool
{
$isWeekend = $dayOfWeek === 0 || $dayOfWeek === 6;
return $hour < OFFICE_OPENS || $hour >= OFFICE_CLOSES || $isWeekend;
}
function onCallRoute(Ticket $ticket): Route
{
$slaMinutes = $ticket->severity === 4 ? 15 : 30;
return new Route('on-call', $slaMinutes, true);
}
function queuedRoute(Ticket $ticket): Route
{
$isFree = $ticket->plan === 'free';
$baseMinutes = $isFree ? 2880 : 480;
$queue = $isFree ? 'community' : 'standard';
return new Route($queue, intdiv($baseMinutes, $ticket->severity), false);
}Why it's worth it
What the change buys you.
A conditional mixes two questions: when does this rule apply, and what does it do. Inline, both are written in the vocabulary of the machine: string comparisons, hour arithmetic, integer division. Extracting them lets you write the decision in the vocabulary of the business: if the ticket needs an on-call page, route it to on-call, otherwise queue it.
The names replace the comment, so there is nothing left to drift out of date. Each extracted predicate is now a single place to change: moving office hours touches isOutsideOfficeHours and nothing else, and redefining what counts as an incident touches isEnterpriseIncident. The branch functions can be tested and reused on their own, for example if a manual escalation button later needs onCallRoute.
Behaviour is unchanged. All the extracted predicates are pure, so splitting the condition and evaluating its parts through function calls gives the same result, and && and || still short-circuit in the same order.
- The top-level function reads as the routing policy itself, in three lines.
- Each business rule (office hours, what counts as an incident, SLA per plan) lives in one named function you can change in isolation.
- Predicates and branch builders can be unit-tested directly instead of only through the full routing function.
- The comment that restated the condition is gone, so it cannot fall out of sync with the code.
Careful with
- Only reorder or split clauses when they are free of side effects. If a clause calls something that writes, logs or is expensive, preserve the original evaluation order exactly.
- Choose names that describe intent, not mechanics.
isOutsideOfficeHourshelps;checkHourAndDayjust moves the puzzle elsewhere. - Do not change the rule while you refactor. If you notice a bug, such as public holidays being ignored, write it down and fix it in a separate commit after the tests are green.
- For a one-clause condition with a one-line branch, extraction can add noise. Apply it where the condition or branches actually need explaining.
Step by step
Small, safe steps, with the tests passing after each.
Pin down current behaviour with tests: an enterprise severity 3 and 4 ticket at 07:00, 18:00 and on a Saturday, the same tickets at 08:00 and 17:00 on a Wednesday, plus free and team tickets at each severity. Run them and confirm they pass.
Extract the time clause
hour < 8 || hour >= 18 || dayOfWeek === 0 || dayOfWeek === 6intoisOutsideOfficeHours(hour, dayOfWeek)and call it from the condition. Run the tests.Replace the literals 8 and 18 inside the new function with named constants
OFFICE_OPENSandOFFICE_CLOSES. Run the tests.Extract
ticket.plan === "enterprise" && ticket.severity >= 3intoisEnterpriseIncident(ticket). Run the tests.Combine the two predicates into
needsOnCallPage(ticket, hour, dayOfWeek), use it as the whole condition, and delete the explanatory comment above theif. Run the tests.Extract the then-branch into
onCallRoute(ticket)and return its result. Run the tests.Extract the else-branch into
queuedRoute(ticket)and return its result. Run the tests.Since the then-branch now returns, drop the
elseand leavereturn queuedRoute(ticket)as the final line. Run the tests one last time.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
How is this different from Consolidate Conditional Expression?
Consolidate Conditional Expression merges several separate checks that lead to the same result into one condition. Decompose Conditional takes a single complicated condition and its branches and extracts them into named functions. They often work together: consolidate first so the rule lives in one if, then decompose it so the rule has a name.
Do the extra function calls hurt performance?
For code like this, the cost is a few function calls per ticket, which is negligible next to any I/O the routing triggers. Many runtimes inline small functions anyway. If profiling ever shows a hot loop where it matters, you can inline that one spot deliberately, but measure first.
Should the extracted functions be public?
Start private or module-local, as in the example. Promote a function only when another caller genuinely needs it, such as a dashboard that shows whether an enterprise ticket would page on-call right now.
What if the conditional is a long if/else-if chain or a switch on type?
You can still decompose each condition and branch, which is often the first safe step. If the same chain on the same type code appears in several places, that points to Replace Conditional with Polymorphism as a follow-up.
How do I present this in an interview?
Say what you see first: a compound condition explained by a comment and two branches with magic numbers. State that you will add characterisation tests, then extract the condition, then each branch, running tests after each step. Interviewers care more about that safe, incremental sequence than about the final names.