Find What Changes and Fence It Off
When the part of a program that changes every week is mixed into the part that shouldn't change, every change risks the rest; finding what changes and giving it a home of its own, behind one wall, is the idea behind almost every design pattern, and it comes with two words worth knowing: coupling and cohesion.
Apprentice · OOP · Software Development · Updated
After this lesson you can
- Find the part of a program most likely to change, and give it a home of its own behind one wall
- Tell loose coupling and high cohesion from their opposites in a short piece of code
Key takeaways
- Ask of every part of an app: how often will this change? The parts that change often get a home of their own.
- Fence off what changes: put it behind one wall, so the rest of the code asks it questions and never needs its details.
- Coupling is how much one piece depends on another's details. Loose coupling means a change in one piece doesn't ripple into others.
- Cohesion is how well the things inside one piece belong together. High cohesion means one piece, one subject.
- Almost every pattern in this course fences off something: a rule, which class to make, or who gets told.
Before this: Code Smells: Symptom, Cause, Cure, where the food truck's special check got one home.
Rosa changes the food truck's specials every week. Last lesson cured the copies of the special check: "is this today's special?" now lives in one method. This week she adds a second special, quesadillas for $5 on Fridays, and next week she'll change them again. The code that charges every customer is about to be edited every week. This lesson finds out why, and ends with the idea behind almost every pattern in this course: find what changes, and fence it off.
The symptom: the price code changes every week
Here is the truck's price code, with this week's change made: the Friday quesadilla was added to IsSpecial. The menu's regular prices sit in a dictionary.
FoodTruck truck = new FoodTruck();
List<(string Day, string Item)> orders = new List<(string Day, string Item)> { ("Monday", "burrito"), ("Friday", "quesadilla"), ("Friday", "burrito") };
foreach ((string day, string item) in orders)
{
string line = quot;{day}: {item} ${truck.Price(item, day)}";
if (truck.IsSpecial(item, day))
{
line += " (special!)";
}
Console.WriteLine(line);
}
class FoodTruck
{
private Dictionary<string, int> menu = new Dictionary<string, int> { ["taco"] = 4, ["burrito"] = 9, ["quesadilla"] = 7, ["drink"] = 2 };
// This week's change: Friday's quesadilla is a special too.
public bool IsSpecial(string item, string day) =>
(item == "burrito" && day == "Monday") || (item == "quesadilla" && day == "Friday");
public int Price(string item, string day)
{
if (IsSpecial(item, day))
{
return 7;
}
return menu[item];
}
}
Monday: burrito $7 (special!)
Friday: quesadilla $7 (special!)
Friday: burrito $9
class FoodTruck {
private Map<String, Integer> menu = Map.of("taco", 4, "burrito", 9, "quesadilla", 7, "drink", 2);
// This week's change: Friday's quesadilla is a special too.
boolean isSpecial(String item, String day) {
return (item.equals("burrito") && day.equals("Monday")) || (item.equals("quesadilla") && day.equals("Friday"));
}
int price(String item, String day) {
if (isSpecial(item, day)) {
return 7;
}
return menu.get(item);
}
}
void main() {
FoodTruck truck = new FoodTruck();
String[][] orders = { { "Monday", "burrito" }, { "Friday", "quesadilla" }, { "Friday", "burrito" } };
for (String[] order : orders) {
String day = order[0];
String item = order[1];
String line = day + ": " + item + " quot; + truck.price(item, day);
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
IO.println(line);
}
}
Monday: burrito $7 (special!)
Friday: quesadilla $7 (special!)
Friday: burrito $9
class FoodTruck:
def __init__(self):
self.menu = {"taco": 4, "burrito": 9, "quesadilla": 7, "drink": 2}
def is_special(self, item, day):
# This week's change: Friday's quesadilla is a special too.
return (item == "burrito" and day == "Monday") or (item == "quesadilla" and day == "Friday")
def price(self, item, day):
if self.is_special(item, day):
return 7
return self.menu[item]
truck = FoodTruck()
for day, item in [("Monday", "burrito"), ("Friday", "quesadilla"), ("Friday", "burrito")]:
line = f"{day}: {item} ${truck.price(item, day)}"
if truck.is_special(item, day):
line += " (special!)"
print(line)
Monday: burrito $7 (special!)
Friday: quesadilla $7 (special!)
Friday: burrito $9
class FoodTruck {
menu = new Map([["taco", 4], ["burrito", 9], ["quesadilla", 7], ["drink", 2]]);
// This week's change: Friday's quesadilla is a special too.
isSpecial(item, day) {
return (item === "burrito" && day === "Monday") || (item === "quesadilla" && day === "Friday");
}
price(item, day) {
if (this.isSpecial(item, day)) {
return 7;
}
return this.menu.get(item);
}
}
const truck = new FoodTruck();
for (const [day, item] of [["Monday", "burrito"], ["Friday", "quesadilla"], ["Friday", "burrito"]]) {
let line = `${day}: ${item} ${truck.price(item, day)}`;
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
console.log(line);
}
Monday: burrito $7 (special!)
Friday: quesadilla $7 (special!)
Friday: burrito $9
class FoodTruck {
menu = new Map<string, number>([["taco", 4], ["burrito", 9], ["quesadilla", 7], ["drink", 2]]);
// This week's change: Friday's quesadilla is a special too.
isSpecial(item: string, day: string): boolean {
return (item === "burrito" && day === "Monday") || (item === "quesadilla" && day === "Friday");
}
price(item: string, day: string): number {
if (this.isSpecial(item, day)) {
return 7;
}
return this.menu.get(item) ?? 0;
}
}
const truck = new FoodTruck();
const orders: [string, string][] = [["Monday", "burrito"], ["Friday", "quesadilla"], ["Friday", "burrito"]];
for (const [day, item] of orders) {
let line = `${day}: ${item} ${truck.price(item, day)}`;
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
console.log(line);
}
Monday: burrito $7 (special!)
Friday: quesadilla $7 (special!)
Friday: burrito $9
Look at the second line. Rosa set Friday's quesadilla at $5, and the truck charges $7, with "(special!)" beside it. The developer added Friday to IsSpecial and missed that Price still says every special costs $7. That's an easy slip, and it will happen again, because of where the specials live.
- The symptom: every new special means editing
Price, the code that charges every customer, and one special is spread over two methods (its day and item in one, its price in the other). - The cause: the part that changes every week (the specials) is mixed into the part that almost never changes (looking up a price).
What would you try?
Give each special its own if in Price. if (item == "quesadilla" && day == "Friday") return 5; fixes Friday. But Price is still edited every week, and each special is still split between IsSpecial and Price, so the two can still disagree.
Write a price method for each day: PriceMonday, PriceFriday. Now the menu board has to pick the right method for the day, and the regular prices are copied into every one of them.
Leave a comment: "update both methods when the specials change!". It's honest, and it doesn't run. The slip above happened next to code that was perfectly clear.
What would really help is if the price code didn't know what the specials are at all, only that there are some, and that it can ask "is there a special on this item today, and what does it cost?"
The idea: fence off what changes
Go through the app and ask of each part: how often will this change?
| Part of the app | How often it changes |
|---|---|
| The specials | every week, whenever Rosa likes |
| The menu's regular prices | a few times a year |
| How a price is looked up, and how a total adds up | almost never |
The thing that changes every week gets a home of its own, behind one wall: a Specials class that holds every special (its day, its item and its price) and answers questions about them. The price code asks it, and never sees the details. Picture a fence around the part that changes: inside the fence, change as often as you like; outside it, nothing has to notice.

Specials specials = new Specials();
specials.Add("Monday", "burrito", 7);
specials.Add("Friday", "quesadilla", 5);
FoodTruck truck = new FoodTruck(specials);
List<(string Day, string Item)> orders = new List<(string Day, string Item)> { ("Monday", "burrito"), ("Friday", "quesadilla"), ("Friday", "burrito") };
foreach ((string day, string item) in orders)
{
string line = quot;{day}: {item} ${truck.Price(item, day)}";
if (truck.IsSpecial(item, day))
{
line += " (special!)";
}
Console.WriteLine(line);
}
// Everything about the specials lives here, behind one fence.
class Specials
{
private Dictionary<(string Day, string Item), int> prices = new Dictionary<(string Day, string Item), int>();
public void Add(string day, string item, int price) => prices[(day, item)] = price;
public bool IsSpecial(string item, string day) => prices.ContainsKey((day, item));
public int Price(string item, string day) => prices[(day, item)];
}
// The price code only asks. It never changes when the specials do.
class FoodTruck
{
private Dictionary<string, int> menu = new Dictionary<string, int> { ["taco"] = 4, ["burrito"] = 9, ["quesadilla"] = 7, ["drink"] = 2 };
private Specials specials;
public FoodTruck(Specials specials)
{
this.specials = specials;
}
public bool IsSpecial(string item, string day) => specials.IsSpecial(item, day);
public int Price(string item, string day)
{
if (specials.IsSpecial(item, day))
{
return specials.Price(item, day);
}
return menu[item];
}
}
Monday: burrito $7 (special!)
Friday: quesadilla $5 (special!)
Friday: burrito $9
// Everything about the specials lives here, behind one fence.
class Specials {
private Map<String, Integer> prices = new HashMap<>();
void add(String day, String item, int price) { prices.put(day + " " + item, price); }
boolean isSpecial(String item, String day) { return prices.containsKey(day + " " + item); }
int price(String item, String day) { return prices.get(day + " " + item); }
}
// The price code only asks. It never changes when the specials do.
class FoodTruck {
private Map<String, Integer> menu = Map.of("taco", 4, "burrito", 9, "quesadilla", 7, "drink", 2);
private Specials specials;
FoodTruck(Specials specials) {
this.specials = specials;
}
boolean isSpecial(String item, String day) {
return specials.isSpecial(item, day);
}
int price(String item, String day) {
if (specials.isSpecial(item, day)) {
return specials.price(item, day);
}
return menu.get(item);
}
}
void main() {
Specials specials = new Specials();
specials.add("Monday", "burrito", 7);
specials.add("Friday", "quesadilla", 5);
FoodTruck truck = new FoodTruck(specials);
String[][] orders = { { "Monday", "burrito" }, { "Friday", "quesadilla" }, { "Friday", "burrito" } };
for (String[] order : orders) {
String day = order[0];
String item = order[1];
String line = day + ": " + item + " quot; + truck.price(item, day);
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
IO.println(line);
}
}
Monday: burrito $7 (special!)
Friday: quesadilla $5 (special!)
Friday: burrito $9
class Specials:
"""Everything about the specials lives here, behind one fence."""
def __init__(self):
self.prices = {}
def add(self, day, item, price):
self.prices[(day, item)] = price
def is_special(self, item, day):
return (day, item) in self.prices
def price(self, item, day):
return self.prices[(day, item)]
class FoodTruck:
"""The price code only asks. It never changes when the specials do."""
def __init__(self, specials):
self.menu = {"taco": 4, "burrito": 9, "quesadilla": 7, "drink": 2}
self.specials = specials
def is_special(self, item, day):
return self.specials.is_special(item, day)
def price(self, item, day):
if self.specials.is_special(item, day):
return self.specials.price(item, day)
return self.menu[item]
specials = Specials()
specials.add("Monday", "burrito", 7)
specials.add("Friday", "quesadilla", 5)
truck = FoodTruck(specials)
for day, item in [("Monday", "burrito"), ("Friday", "quesadilla"), ("Friday", "burrito")]:
line = f"{day}: {item} ${truck.price(item, day)}"
if truck.is_special(item, day):
line += " (special!)"
print(line)
Monday: burrito $7 (special!)
Friday: quesadilla $5 (special!)
Friday: burrito $9
// Everything about the specials lives here, behind one fence.
class Specials {
prices = new Map();
add(day, item, price) { this.prices.set(`${day} ${item}`, price); }
isSpecial(item, day) { return this.prices.has(`${day} ${item}`); }
price(item, day) { return this.prices.get(`${day} ${item}`); }
}
// The price code only asks. It never changes when the specials do.
class FoodTruck {
menu = new Map([["taco", 4], ["burrito", 9], ["quesadilla", 7], ["drink", 2]]);
constructor(specials) {
this.specials = specials;
}
isSpecial(item, day) {
return this.specials.isSpecial(item, day);
}
price(item, day) {
if (this.specials.isSpecial(item, day)) {
return this.specials.price(item, day);
}
return this.menu.get(item);
}
}
const specials = new Specials();
specials.add("Monday", "burrito", 7);
specials.add("Friday", "quesadilla", 5);
const truck = new FoodTruck(specials);
for (const [day, item] of [["Monday", "burrito"], ["Friday", "quesadilla"], ["Friday", "burrito"]]) {
let line = `${day}: ${item} ${truck.price(item, day)}`;
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
console.log(line);
}
Monday: burrito $7 (special!)
Friday: quesadilla $5 (special!)
Friday: burrito $9
// Everything about the specials lives here, behind one fence.
class Specials {
prices = new Map<string, number>();
add(day: string, item: string, price: number): void { this.prices.set(`${day} ${item}`, price); }
isSpecial(item: string, day: string): boolean { return this.prices.has(`${day} ${item}`); }
price(item: string, day: string): number { return this.prices.get(`${day} ${item}`) ?? 0; }
}
// The price code only asks. It never changes when the specials do.
class FoodTruck {
menu = new Map<string, number>([["taco", 4], ["burrito", 9], ["quesadilla", 7], ["drink", 2]]);
specials: Specials;
constructor(specials: Specials) {
this.specials = specials;
}
isSpecial(item: string, day: string): boolean {
return this.specials.isSpecial(item, day);
}
price(item: string, day: string): number {
if (this.specials.isSpecial(item, day)) {
return this.specials.price(item, day);
}
return this.menu.get(item) ?? 0;
}
}
const specials = new Specials();
specials.add("Monday", "burrito", 7);
specials.add("Friday", "quesadilla", 5);
const truck = new FoodTruck(specials);
const orders: [string, string][] = [["Monday", "burrito"], ["Friday", "quesadilla"], ["Friday", "burrito"]];
for (const [day, item] of orders) {
let line = `${day}: ${item} ${truck.price(item, day)}`;
if (truck.isSpecial(item, day)) {
line += " (special!)";
}
console.log(line);
}
Monday: burrito $7 (special!)
Friday: quesadilla $5 (special!)
Friday: burrito $9
The Friday quesadilla is $5 now, and look at what a new special costs: one Add line, written wherever Rosa's tablet sets the specials. FoodTruck isn't opened. Each special is one row of data, so its day, its item and its price can't drift apart.
Try it. Add a third special, tacos for $3 on Tuesdays, without touching FoodTruck or Specials. A taco on Tuesday should print Tuesday: taco $3 (special!).
Where the languages differ. C# and Python key the dictionary by a pair, (day, item), which both languages compare by value. Java, JavaScript and TypeScript join the two into one text key, "Friday quesadilla", since their maps compare arrays and objects by identity, not by what's in them.
Two words for what happened
Coupling is how much one piece of code depends on another's details. Think of the cords behind a TV stand: every cord tangled through every other, so pulling out one cable drags three more with it. The old FoodTruck was tightly coupled to this week's specials: it knew each special's day, item and price, so changing a special meant changing it. Now it knows only "ask the specials", which is loose coupling: the specials can change and FoodTruck doesn't feel it.
Cohesion is how well the things inside one piece belong together. Think of a kitchen drawer with only the cooking spoons in it, next to the junk drawer that has spoons, batteries and a takeout menu. The old FoodTruck was a junk drawer: menu prices and this week's promotions, mixed. Specials is a tidy drawer: everything about specials, and nothing else. That's high cohesion.

The two usually move together. When you fence off what changes, the fenced part gets high cohesion (one subject) and the rest gets loose coupling (it only asks). Good design aims for both.
Where you'll meet this idea again
In your textbook this idea is often called encapsulate what varies: to encapsulate is to put something in a capsule, behind a wall, and what varies is what changes. It's behind almost every pattern in this course. A Simple Factory fences off which class gets made; a Strategy fences off a rule that keeps changing; an Observer fences off who gets told. Every role diagram in the course draws the same dashed fence around the part that varies, because that fence is the pattern's whole point.
When to leave it alone
Fencing something off costs a class, and a jump for the reader ("where do the specials come from?"). It's worth it for a part that really changes. A rule that has been the same for three years, or a list of two things that will always be two, can stay where it is. Ask the people who run the business what changes, and fence off that; the rest can wait until it starts to change.
Check yourself
2 questions to try on the lesson page.
So what
Find the part of the app that changes most often, and give it a home behind one wall. Changes then land in one place, the rest of the code keeps working without noticing, and you've learned the idea most patterns are built on.