You get a ticket that sounds small: add a new membership tier, support a new currency, rename a status. Then you open the pull request and it touches nine files, each with a two-line tweak. That is Shotgun Surgery. One decision has been spread thin across the codebase, so every change to it is a scattershot of edits. The danger is not the typing. It is the edit you forget. When the knowledge lives in many places, nothing tells you that you have found them all, and the one you miss usually fails quietly in production. In interviews this smell comes up when you are asked how you would make a design easier to change. Being able to name it, spot it in a diff and explain how to consolidate it shows you think about the cost of change, not just correctness today.
Signs
How to spot it in a review.
- A routine feature request, such as adding an enum value, produces a diff that touches many files with tiny edits in each.
- The same string or code, like
"dedicated"or"EUR", is compared against in switch statements or if chains across several modules. - Git history shows the same group of files changing together in commit after commit.
- Bugs appear where one place was updated and a sibling place was not, often hidden by a default branch.
- Code reviewers regularly ask "did you also update X?" and the answer depends on someone remembering.
What it looks like
A typical case, in three languages.
// BEFORE: tier knowledge scattered across four modules
// billing/pricing.ts
export function monthlyPriceCents(tier: string): number {
switch (tier) {
case "flex": return 9_900;
case "dedicated": return 34_900;
case "office": return 89_900;
default: throw new Error(`Unknown tier: ${tier}`);
}
}
// booking/limits.ts
export function maxBookingsPerWeek(tier: string): number {
if (tier === "flex") return 3;
if (tier === "dedicated") return 7;
return Infinity; // office
}
// access/doors.ts
export function canEnterAt(tier: string, hour: number): boolean {
if (tier === "flex") return hour >= 8 && hour < 19;
return true;
}
// invoices/labels.ts
export function invoiceLabel(tier: string): string {
if (tier === "office") return "Private Office";
if (tier === "dedicated") return "Dedicated Desk";
return "Flex Desk";
}
// AFTER: one module owns everything about a tier
// membership/tier.ts
export class MembershipTier {
constructor(
readonly code: string,
readonly label: string,
readonly monthlyPriceCents: number,
readonly maxBookingsPerWeek: number,
readonly openHour: number,
readonly closeHour: number,
) {}
canEnterAt(hour: number): boolean {
return hour >= this.openHour && hour < this.closeHour;
}
static fromCode(code: string): MembershipTier {
const tier = TIERS.get(code);
if (!tier) throw new Error(`Unknown tier: ${code}`);
return tier;
}
}
const TIERS = new Map<string, MembershipTier>([
["flex", new MembershipTier("flex", "Flex Desk", 9_900, 3, 8, 19)],
["dedicated", new MembershipTier("dedicated", "Dedicated Desk", 34_900, 7, 0, 24)],
["office", new MembershipTier("office", "Private Office", 89_900, Infinity, 0, 24)],
]);
// Callers elsewhere:
// const tier = MembershipTier.fromCode(member.tierCode);
// invoice.addLine(tier.label, tier.monthlyPriceCents);
// if (!tier.canEnterAt(now.getHours())) door.deny();# BEFORE: tier knowledge scattered across four modules
import math
from dataclasses import dataclass
# billing/pricing.py
def monthly_price_cents(tier: str) -> int:
if tier == "flex":
return 9_900
if tier == "dedicated":
return 34_900
if tier == "office":
return 89_900
raise ValueError(f"Unknown tier: {tier}")
# booking/limits.py
def max_bookings_per_week(tier: str) -> float:
if tier == "flex":
return 3
if tier == "dedicated":
return 7
return math.inf # office
# access/doors.py
def can_enter_at(tier: str, hour: int) -> bool:
if tier == "flex":
return 8 <= hour < 19
return True
# invoices/labels.py
def invoice_label(tier: str) -> str:
if tier == "office":
return "Private Office"
if tier == "dedicated":
return "Dedicated Desk"
return "Flex Desk"
# AFTER: one module owns everything about a tier
# membership/tier.py
@dataclass(frozen=True)
class MembershipTier:
code: str
label: str
monthly_price_cents: int
max_bookings_per_week: float
open_hour: int
close_hour: int
def can_enter_at(self, hour: int) -> bool:
return self.open_hour <= hour < self.close_hour
@classmethod
def from_code(cls, code: str) -> "MembershipTier":
try:
return _TIERS[code]
except KeyError:
raise ValueError(f"Unknown tier: {code}") from None
_TIERS = {
t.code: t
for t in (
MembershipTier("flex", "Flex Desk", 9_900, 3, 8, 19),
MembershipTier("dedicated", "Dedicated Desk", 34_900, 7, 0, 24),
MembershipTier("office", "Private Office", 89_900, math.inf, 0, 24),
)
}
# Callers elsewhere:
# tier = MembershipTier.from_code(member.tier_code)
# invoice.add_line(tier.label, tier.monthly_price_cents)
# if not tier.can_enter_at(now.hour): door.deny()<?php
// BEFORE: tier knowledge scattered across four modules
// billing/pricing.php
function monthlyPriceCents(string $tier): int
{
return match ($tier) {
'flex' => 9900,
'dedicated' => 34900,
'office' => 89900,
default => throw new InvalidArgumentException("Unknown tier: {$tier}"),
};
}
// booking/limits.php
function maxBookingsPerWeek(string $tier): float
{
if ($tier === 'flex') return 3;
if ($tier === 'dedicated') return 7;
return INF; // office
}
// access/doors.php
function canEnterAt(string $tier, int $hour): bool
{
if ($tier === 'flex') return $hour >= 8 && $hour < 19;
return true;
}
// invoices/labels.php
function invoiceLabel(string $tier): string
{
if ($tier === 'office') return 'Private Office';
if ($tier === 'dedicated') return 'Dedicated Desk';
return 'Flex Desk';
}
// AFTER: one class owns everything about a tier
// membership/MembershipTier.php
final class MembershipTier
{
public function __construct(
public readonly string $code,
public readonly string $label,
public readonly int $monthlyPriceCents,
public readonly float $maxBookingsPerWeek,
public readonly int $openHour,
public readonly int $closeHour,
) {}
public function canEnterAt(int $hour): bool
{
return $hour >= $this->openHour && $hour < $this->closeHour;
}
public static function fromCode(string $code): self
{
return match ($code) {
'flex' => new self('flex', 'Flex Desk', 9900, 3, 8, 19),
'dedicated' => new self('dedicated', 'Dedicated Desk', 34900, 7, 0, 24),
'office' => new self('office', 'Private Office', 89900, INF, 0, 24),
default => throw new InvalidArgumentException("Unknown tier: {$code}"),
};
}
}
// Callers elsewhere:
// $tier = MembershipTier::fromCode($member->tierCode);
// $invoice->addLine($tier->label, $tier->monthlyPriceCents);
// if (!$tier->canEnterAt((int) date('G'))) $door->deny();DeskHop, a coworking booking platform, wants to launch a fourth tier, Studio. In the before version that means four edits in four modules owned by three teams. Worse, three of those functions end in a default branch, so if you forget booking limits, Studio members silently get unlimited bookings, and if you forget door access they get 24-hour entry. After moving every tier fact into MembershipTier, adding Studio is one new line, and an unknown code fails loudly in one place instead of falling through quietly.
Why it happens
How code ends up like this.
- Every forgotten spot is a latent bug, and default branches or fallback values tend to hide the omission until a customer hits it.
- Small features turn into cross-team pull requests, which slows delivery and makes reviews harder because the real change is diluted across many files.
- The rule has no single home, so nobody can read one place and know how a tier, currency or status actually behaves.
- Onboarding suffers: new engineers only learn the full list of places to touch by breaking something or asking someone who remembers.
Treatment
The refactorings that cure it, and when to choose each.
- Move Function: Put Behaviour Next to the Data It Uses
Functions that all reason about the same concept live in different modules. Move them next to each other, ideally onto the type that represents the concept.
- Extract Class: Split a Class That Does Two Jobs
The scattered data and behaviour form a coherent concept that no class owns yet, like a membership tier. Give it a class and let callers ask it questions.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
A raw string or number such as a tier code or currency code is passed around and interpreted everywhere. Wrap it so the interpretation happens once.
- Replace Conditional with Polymorphism: One Class per Case
The variants differ in behaviour, not just values, and the same switch on type is repeated in several places. Each variant then implements its own behaviour.
- Inline Class: Fold a Class That No Longer Earns Its Keep
The pieces are split across small classes that no longer earn their keep. Fold them together so the change lands in one class.
- Inline Function: Remove Indirection That Adds Nothing
Thin wrapper functions in several layers each forward the same detail. Inlining them removes places that must be edited in lockstep.
Payoff
What you get once it's gone.
- A change to the concept becomes a change to one file, which is easier to write, review and revert.
- Omissions turn into compile errors or loud runtime failures instead of silent wrong behaviour.
- The rule is readable in one place, so product questions like what a Flex member gets can be answered by reading a single class.
- Tests can target the consolidated class directly rather than re-checking each scattered function.
When to leave it
Sometimes it's not worth fixing.
- The edits are spread because the layers really are independent, such as a database migration, an API schema and a UI form for a new field. Consolidating them would couple layers that should stay separate.
- The concept is genuinely stable, for example the days of the week, and the cost of gathering it exceeds the cost of the rare change.
- Generated code or framework conventions require the repetition, and the generator or convention is the real single source of truth.
Common questions
Short answers to the usual doubts.
How is Shotgun Surgery different from Divergent Change?
They are mirror images. Divergent Change is one module that changes for many unrelated reasons, so it needs splitting. Shotgun Surgery is one reason that forces changes in many modules, so the pieces need gathering. The fix for one can create the other if you split or merge too aggressively, so aim for each reason to change mapping to one place.
How do I find Shotgun Surgery in an existing codebase?
Look at version control. Files that are repeatedly modified in the same commits are strong candidates, and many teams run simple change-coupling queries over git log for this. You can also search for every comparison against a specific string or enum value: if it shows up in many modules, the knowledge is scattered.
Is a config file or lookup table enough to fix it?
Often it is a good first step, because it puts the values in one place. But if behaviour still branches on the code in several modules, the smell remains. The goal is that callers ask the concept for an answer rather than deciding for themselves based on its code.
Will consolidating everything into one class create a God Class?
It can if you pull in unrelated responsibilities. Gather only what changes together for the same reason. A tier class that knows price, limits and access hours is cohesive; one that also sends emails and renders invoices is not.
How should I talk about this smell in an interview?
Describe it in terms of change cost: a single requirement change forces edits in many places, and the risk is the place you miss. Then give a concrete fix such as moving the scattered decisions onto one type, and mention the trade-off that you should not merge things that change for different reasons.