Patterns in Code Reviews and Interviews
Naming a pattern in a code review helps only when it comes with the problem and is said kindly, and naming one in an interview counts only when it comes with a real story; this lesson shows how to do both, so the names you've learned make you easier to work with.
Journeyman · Software Development · OOP · Updated
After this lesson you can
- Name a pattern in a code review kindly: the problem first, then the pattern, with a link and an offer to help
- Answer an interview question about a pattern you've used with a real story: the problem, the choices, the trade-off and the result
Key takeaways
- In a review, name the problem before the pattern, point to the card, and offer to help; ask, don't order.
- Don't suggest a pattern where a smaller fix will do: "this needs a factory" for one new class is pattern fever.
- When someone names a pattern you don't know, ask what problem it solves here; that conversation is what the name is for.
- In an interview, answer with a story: the problem, what you tried, what you chose and why, what it cost, and how it turned out.
Before this: Writing a Pattern Card Your Team Will Read, and the exercise The Coupon Rules, whose story this lesson uses.
Knowing the names of patterns changes how you talk at work, and it can go well or badly. Said well, "the Row Importer would handle this" saves a teammate an afternoon. Said badly, "this needs a Strategy" makes them stop asking you questions. The two places it matters most are code reviews, where you comment on a teammate's change, and job interviews, where someone asks about the patterns you've used. This lesson is about saying the names in a way that helps.
The pull request
At Summit Gym, Theo has opened a pull request: a proposed change, waiting for a teammate to read it before it's merged into the team's shared code. That reading, with comments, is a code review. Here is Theo's change, a fourth importer for the equipment team:
// Theo's pull request: a fourth importer, for the equipment team.
string equipmentFile = "item,room\nmats,studio A\n\nbikes,studio B";
Console.WriteLine("Equipment: " + string.Join(", ", ImportEquipment(equipmentFile)));
List<string> ImportEquipment(string text)
{
List<string> equipment = new List<string>();
foreach (string line in text.Trim().Split('\n'))
{
if (line.Trim() == "") { continue; }
string[] parts = line.Split(',').Select(part => part.Trim()).ToArray();
equipment.Add( quot;{parts[0]} in {parts[1]}");
}
return equipment;
}
Equipment: item in room, mats in studio A, bikes in studio B
// Theo's pull request: a fourth importer, for the equipment team.
List<String> importEquipment(String text) {
List<String> equipment = new ArrayList<>();
for (String line : text.strip().lines().toList()) {
if (line.isBlank()) { continue; }
String[] parts = line.split(",");
equipment.add(parts[0].strip() + " in " + parts[1].strip());
}
return equipment;
}
void main() {
String equipmentFile = "item,room\nmats,studio A\n\nbikes,studio B";
IO.println("Equipment: " + String.join(", ", importEquipment(equipmentFile)));
}
Equipment: item in room, mats in studio A, bikes in studio B
def import_equipment(text):
"""Theo's pull request: a fourth importer, for the equipment team."""
equipment = []
for line in text.strip().split("\n"):
if line.strip() == "":
continue
item, room = [part.strip() for part in line.split(",")]
equipment.append(f"{item} in {room}")
return equipment
equipment_file = "item,room\nmats,studio A\n\nbikes,studio B"
print("Equipment: " + ", ".join(import_equipment(equipment_file)))
Equipment: item in room, mats in studio A, bikes in studio B
// Theo's pull request: a fourth importer, for the equipment team.
function importEquipment(text) {
const equipment = [];
for (const line of text.trim().split("\n")) {
if (line.trim() === "") { continue; }
const [item, room] = line.split(",").map((part) => part.trim());
equipment.push(`${item} in ${room}`);
}
return equipment;
}
const equipmentFile = "item,room\nmats,studio A\n\nbikes,studio B";
console.log("Equipment: " + importEquipment(equipmentFile).join(", "));
Equipment: item in room, mats in studio A, bikes in studio B
// Theo's pull request: a fourth importer, for the equipment team.
function importEquipment(text: string): string[] {
const equipment: string[] = [];
for (const line of text.trim().split("\n")) {
if (line.trim() === "") { continue; }
const [item, room] = line.split(",").map((part) => part.trim());
equipment.push(`${item} in ${room}`);
}
return equipment;
}
const equipmentFile = "item,room\nmats,studio A\n\nbikes,studio B";
console.log("Equipment: " + importEquipment(equipmentFile).join(", "));
Equipment: item in room, mats in studio A, bikes in studio B
The first item printed is "item in room": the header line became an item, because this copy doesn't skip it. And the team already has the Row Importer, which skips it for you.
What would you try?
Three comments you could leave:
- "This is wrong. Use the Row Importer." Correct, and it reads as a telling-off. It doesn't say what's wrong or where the Row Importer is, and Sam may not know it exists.
- "Have you considered applying the Template Method pattern here?" A pattern name with no problem attached. It sounds like a quiz, and Sam has to work out what you saw.
- Approve it. It runs, and the header bug goes out to the equipment team.
A comment that helps says the problem, then what's already there, with a link and an offer:
The first row comes out as "item in room": the header line isn't skipped. We hit the same thing in the members, instructors and class-times importers, and pulled the shared steps into the Row Importer (docs/patterns/row-importer.md). Would it fit here? Then this is one line, with the header and blank lines handled. The trimming here is right, by the way. Happy to pair on it if that helps.
Naming a pattern in a review
- The problem first, then the pattern. "The header isn't skipped" is something Theo can check in a minute. The pattern's name is the suggestion that follows.
- Link the card, and ask. "Would it fit here?" leaves room for a reason you can't see, such as a file with commas inside its values.
- Say what's good, too. Real praise, for something specific, makes the rest easy to hear.
- Only when it pays. Suggesting a factory for one new class, or a strategy for one rule that never changes, is pattern fever (Pattern Fever: When a Pattern Makes Code Worse). Sometimes the best review comment is "pull this into a method".
- When someone names a pattern you don't know, ask: "What problem does it solve here?" That isn't a weakness. The name is meant to start exactly that conversation.
In an interview: a story, not a definition
Interviewers often ask, "Tell me about a design pattern you've used." A recited definition, such as "Interpreter is a pattern where each rule is a class", shows you read about it. A story shows you can use it. Many interviewers expect the story in a shape called the STAR method: the Situation, your Task, the Action you took, and the Result. Here is one, from this course's Exercise: The Coupon Rules:
- Situation: an online store's marketing team waited for a developer every time they wanted a new coupon.
- Task: let them build their own coupon rules on an admin screen, and show each rule in words.
- Action: I tried a table of columns first, and it couldn't say "or". So I made each rule a tree of small pieces that each answer "does this order qualify?", which is the Interpreter pattern, and added describing the rule as a visitor.
- Result: new coupons need no code. It cost five small classes and the screen that builds the trees, and if they wanted to type rules as text, I'd add a parser library.
The Action and Result are where judgment shows: what you tried and dropped, and what your choice cost. Interviewers listen for both. And it's fine to say a story comes from a course exercise: it's still real work you did.
Here's the story's code at its smallest, in case the interviewer asks you to sketch it:
// TRAIL10: total over $50 and (has a shoe or has a jacket), as a tree of small pieces.
IRule trail10 = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")));
Order maya = new Order(132, new List<string> { "shoe", "socks" });
Console.WriteLine( quot;TRAIL10 for Maya's $132 order: {(trail10.Qualifies(maya) ? "yes" : "no")}");
interface IRule { bool Qualifies(Order order); }
record Order(int Total, List<string> Kinds);
class TotalOver(int amount) : IRule { public bool Qualifies(Order order) => order.Total > amount; }
class Has(string kind) : IRule { public bool Qualifies(Order order) => order.Kinds.Contains(kind); }
class And(IRule left, IRule right) : IRule { public bool Qualifies(Order order) => left.Qualifies(order) && right.Qualifies(order); }
class Or(IRule left, IRule right) : IRule { public bool Qualifies(Order order) => left.Qualifies(order) || right.Qualifies(order); }
TRAIL10 for Maya's $132 order: yes
interface Rule { boolean qualifies(Order order); }
record Order(int total, List<String> kinds) {}
record TotalOver(int amount) implements Rule { public boolean qualifies(Order order) { return order.total() > amount; } }
record Has(String kind) implements Rule { public boolean qualifies(Order order) { return order.kinds().contains(kind); } }
record And(Rule left, Rule right) implements Rule { public boolean qualifies(Order order) { return left.qualifies(order) && right.qualifies(order); } }
record Or(Rule left, Rule right) implements Rule { public boolean qualifies(Order order) { return left.qualifies(order) || right.qualifies(order); } }
void main() {
// TRAIL10: total over $50 and (has a shoe or has a jacket), as a tree of small pieces.
Rule trail10 = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")));
Order maya = new Order(132, List.of("shoe", "socks"));
IO.println("TRAIL10 for Maya's $132 order: " + (trail10.qualifies(maya) ? "yes" : "no"));
}
TRAIL10 for Maya's $132 order: yes
class Order:
def __init__(self, total, kinds):
self.total = total
self.kinds = kinds
class TotalOver:
def __init__(self, amount):
self.amount = amount
def qualifies(self, order):
return order.total > self.amount
class Has:
def __init__(self, kind):
self.kind = kind
def qualifies(self, order):
return self.kind in order.kinds
class And:
def __init__(self, left, right):
self.left, self.right = left, right
def qualifies(self, order):
return self.left.qualifies(order) and self.right.qualifies(order)
class Or:
def __init__(self, left, right):
self.left, self.right = left, right
def qualifies(self, order):
return self.left.qualifies(order) or self.right.qualifies(order)
# TRAIL10: total over $50 and (has a shoe or has a jacket), as a tree of small pieces.
trail10 = And(TotalOver(50), Or(Has("shoe"), Has("jacket")))
maya = Order(132, ["shoe", "socks"])
print(f"TRAIL10 for Maya's $132 order: {'yes' if trail10.qualifies(maya) else 'no'}")
TRAIL10 for Maya's $132 order: yes
class TotalOver { constructor(amount) { this.amount = amount; } qualifies(order) { return order.total > this.amount; } }
class Has { constructor(kind) { this.kind = kind; } qualifies(order) { return order.kinds.includes(this.kind); } }
class And { constructor(left, right) { this.left = left; this.right = right; } qualifies(order) { return this.left.qualifies(order) && this.right.qualifies(order); } }
class Or { constructor(left, right) { this.left = left; this.right = right; } qualifies(order) { return this.left.qualifies(order) || this.right.qualifies(order); } }
// TRAIL10: total over $50 and (has a shoe or has a jacket), as a tree of small pieces.
const trail10 = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")));
const maya = { total: 132, kinds: ["shoe", "socks"] };
console.log(`TRAIL10 for Maya's $132 order: ${trail10.qualifies(maya) ? "yes" : "no"}`);
TRAIL10 for Maya's $132 order: yes
interface Order { total: number; kinds: string[]; }
interface Rule { qualifies(order: Order): boolean; }
class TotalOver implements Rule { amount: number; constructor(amount: number) { this.amount = amount; } qualifies(order: Order): boolean { return order.total > this.amount; } }
class Has implements Rule { kind: string; constructor(kind: string) { this.kind = kind; } qualifies(order: Order): boolean { return order.kinds.includes(this.kind); } }
class And implements Rule { left: Rule; right: Rule; constructor(left: Rule, right: Rule) { this.left = left; this.right = right; } qualifies(order: Order): boolean { return this.left.qualifies(order) && this.right.qualifies(order); } }
class Or implements Rule { left: Rule; right: Rule; constructor(left: Rule, right: Rule) { this.left = left; this.right = right; } qualifies(order: Order): boolean { return this.left.qualifies(order) || this.right.qualifies(order); } }
// TRAIL10: total over $50 and (has a shoe or has a jacket), as a tree of small pieces.
const trail10 = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")));
const maya: Order = { total: 132, kinds: ["shoe", "socks"] };
console.log(`TRAIL10 for Maya's $132 order: ${trail10.qualifies(maya) ? "yes" : "no"}`);
TRAIL10 for Maya's $132 order: yes
Design questions work the same way. Asked "how would you let users write their own rules?", say the problem back, give two options and what each costs, pick one, and say when you'd change your mind. Name the pattern as you go, as vocabulary, not as the answer.
When not to name a pattern
- In a review, when a plain fix will do. Name the smaller fix.
- In an interview, when the question is about the problem. Answer the problem; the name is a bonus.
- Anywhere, to sound clever. If the name doesn't make the conversation shorter, leave it out.
Check yourself
2 questions to try on the lesson page.
So what
A pattern's name is a shortcut for a conversation about a problem. In a review, start with the problem and offer the name as help; in an interview, tell the story the name belongs to. Either way, the problem comes first, as it has all through this course.