Clean code: extract until it reads
Turn a long method into named steps you can read from top to bottom.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–7Payoff
Step 8C# bonus
Steps 9–10Recap
Steps 11–12The code: before and after
Before
class Checkout
{
public string Confirm(Order order)
{
if (order.Items.Count == 0)
{
throw new ArgumentException("No items");
}
decimal total = 0;
foreach (var item in order.Items)
{
total += item.Price * item.Qty;
}
total += total < 50.0m ? 4.99m : 0;
total += order.Express ? 7.50m : 0;
return $"{order.Items.Count} items, ${total:0.00}";
}
}After
class Checkout
{
public string Confirm(Order order)
{
RequireItems(order);
decimal goods = Subtotal(order);
decimal discount = MemberDiscount(order, goods);
decimal total = goods - discount + DeliveryFee(order, goods);
return $"{order.Items.Count} items, ${total:0.00}";
}
private void RequireItems(Order order)
{
if (order.Items.Count == 0)
{
throw new ArgumentException("No items");
}
}
private decimal Subtotal(Order order) =>
order.Items.Sum(item => item.Price * item.Qty);
private decimal MemberDiscount(Order order, decimal goods)
{
return order.Member ? goods * 0.10m : 0;
}
private decimal DeliveryFee(Order order, decimal goods)
{
decimal fee = 0;
fee += goods < 50.0m ? 4.99m : 0;
fee += order.Express ? 7.50m : 0;
return fee;
}
}Transcript, step by step
Problem
Step 1: A checkout that works Before
This method confirms a grocery order and returns the line the customer sees. It checks there are items, adds up the prices, adds delivery, and builds the message. Delivery is free from fifty dollars, express adds seven fifty, and the tests pass.
Step 2: A discount in the wrong place Code smell
Members now get ten percent off their groceries. Someone adds the discount near the end, because total looks like the number to change. By that line, total already includes delivery, so members get ten percent off the delivery fees too, and nobody asked for that. This is a long method, one body doing several jobs, so you have to read every line to find the one you need. It checks the order here, adds up the goods here, adds delivery here, and builds the message here. Total means the goods at the top and the goods plus fees at the bottom, and only reading every line tells you which one you've got.
Step 3: Undo, then extract Plan
Let's back that change out. Extract Method takes a few lines that do one job and moves them into a method named after that job. We'll keep extracting until confirm reads like a list of steps, and then the discount should have an obvious place.
Refactor
Step 4: Pull out the guard Extract Method
The first lines guard against an empty order, so they move into a method called require items. Confirm now opens with one line that says what it checks, and you only read the error handling when you care about it.
Step 5: Pull out the subtotal Extract Method
The loop adds up what the groceries cost, so it becomes a method called subtotal. Inside it, the running number gets its own name, sum, so it can't be mixed up with the total in confirm. Back in confirm, total now starts from the subtotal in a single line.
Step 6: One name per meaning Split Variable
Total was doing two jobs, holding the goods first and the amount to pay after that. So the goods get a variable of their own, and total starts from it. The free delivery check now reads the goods, which is what it meant all along.
Step 7: Pull out delivery Extract Method
The two delivery lines move into a method called delivery fee, and it takes the goods to check the free delivery limit. Total is now the goods plus the delivery fee, and you can read that straight off the line. Read confirm from the top and you get the steps in order, because it requires items, adds up the goods, adds the fee, and returns the message. The message line already says what it does, so it stays where it is, and that's the point where you stop extracting.
Payoff
Step 8: The discount, in the right place Payoff
Now the discount comes back, as a method called member discount that takes ten percent off the goods. In confirm, it comes off the goods and the delivery fee is added after, so members only save on what they buy. The jobs that were tangled together now sit apart, with the check here, the goods here, delivery here, and the message here. Require items, subtotal and delivery fee didn't change, so the fees can't pick up the discount by accident.
C# bonus
Step 9: A loop that only adds LINQ Sum
Subtotal still keeps a running sum by hand, with a variable, a loop and a return around one line of math. LINQ's Sum adds up a list in one expression, and a method that is one expression can use an arrow instead of braces.
Step 10: One expression, one arrow LINQ Sum
Now Subtotal sums each item's price times its quantity, in one line. It's the same math, and confirm still calls subtotal, so nothing outside the method changed.
Recap
Step 11: Where we started, where we ended Before / after
On the left, one method checked the order, added up the prices, charged delivery and built the message. Total changed meaning halfway down, and that's why the discount landed on the fees. On the right, confirm reads as the steps of a checkout. Each step it calls is a small method below, named for its job.
Step 12: When to reach for it Takeaways
Extract a method when you have to read all of one to find the part you need to change. Leave lines alone when they already say what they do, because a method named after them would only repeat them. You'll spot the need in long methods, in comments that label each section, and in one variable that changes meaning on the way down.