I'll Be Backend
Principles · Go

Clean code: rename for intent

Make every name say what it means, so the next change lands right.

15 steps4 chapters~4 min at 1.25×#naming#readability#rename#magic numbers
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Go video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–12

Payoff

Step 13

Recap

Steps 14–15

The code: before and after

Before

import "fmt"

type Loan struct {
	D int
	F bool
}

func calc(l Loan) float64 {
	x := l.D - 14
	if x <= 0 {
		return 0
	}
	r := 0.25
	if l.F {
		r = 0.10
	}
	return min(float64(x)*r, 10.0)
}

func receipt(l Loan) string {
	return fmt.Sprintf("Late fine: $%.2f", calc(l))
}

After

import "fmt"

type Loan struct {
	DaysOut int
	Student bool
}

const (
	loanDays     = 14
	graceDays    = 3
	studentRate  = 0.10
	standardRate = 0.25
	maxFine      = 10.0
)

func overdueFine(loan Loan) float64 {
	daysLate := loan.DaysOut - loanDays
	if daysLate <= graceDays {
		return 0
	}
	dailyRate := standardRate
	if loan.Student {
		dailyRate = studentRate
	}
	return min(float64(daysLate)*dailyRate, maxFine)
}

func receipt(loan Loan) string {
	return fmt.Sprintf("Late fine: $%.2f", overdueFine(loan))
}

Transcript, step by step

Problem

Step 1: A late fine that works Before

This function works out the late fine on a library book. It subtracts a number from the loan, picks a rate, and caps the result. The receipt function prints that fine on your receipt, and the tests pass.

Step 2: A grace period that never applies Code smell

The library now wants a grace period, so a book up to three days late costs nothing. Someone reads D as days late and adds a check at the top. But D counts days since checkout, so a book three days late has been out seventeen days, and the grace period never applies. These are names that hide intent, where a name says nothing about what its value means, so you have to work it out from the math. You can see it in D here, F here, x here, r here, and in calc, the function's own name. Every reader has to decode the code again, and the one who guessed wrong just shipped a rule that never runs.

Step 3: Undo, then rename Plan

Let's back that change out. Renaming for intent means giving each value a name that says what it is in the library's own words. A rename doesn't change what the code does, so each one is safe, and after them the grace period should be one obvious line.

Refactor

Step 4: D becomes DaysOut Rename Field

First, D becomes days out, the number of days since checkout. Your editor's rename updates every use, so the line that reads it changes too, and it now says days out minus fourteen.

Step 5: F becomes Student Rename Field

The only clue to what F meant was the cheaper rate it picks. It's true for student cards, so we call it student, and the loan now describes itself.

Step 6: x becomes daysLate Rename Variable

Days out minus the loan period is how many days late the book is, so x becomes days late. The check below it now reads as the rule itself, because a book that isn't late pays nothing.

Step 7: r becomes dailyRate Rename Variable

r is what each late day costs, so it becomes daily rate. Read the last line now and you hear the rule, days late times the daily rate.

Step 8: l becomes loan Rename Parameter

A lone l looks like the number one in many fonts, and it tells you nothing the type doesn't. So both parameters become loan.

Step 9: Name the loan period Replace Magic Number

Numbers need names too, and fourteen is the loan period, so it becomes a constant called Loan Days. When the library changes how long you can keep a book, you search for loan days and land on the right line.

Step 10: Name the two rates Replace Magic Number

Ten cents and twenty-five cents become Student Rate and Standard Rate. The lines that pick the rate now read as the rule, because everyone pays the standard rate and students pay the student rate.

Step 11: Name the cap Replace Magic Number

The last bare number is ten dollars, the most a fine can reach, so it becomes Max Fine. Every rule the library set now has a name at the top of the file.

Step 12: calc becomes overdueFine Rename Function

Calc only says the function computes something, and every function does. Overdue fine says what you get back, so the call on the receipt reads like the receipt itself.

Payoff

Step 13: The grace period, right the first time Payoff

Now we add the grace period again, as a constant called Grace Days. The rule is about days late, and that name is right there, so the change goes into the check that already exists. The names that hid intent are gone, with days out here, student here, days late here, and daily rate here. The loan and the receipt function didn't change, and the old mistake is hard to make, because days late is the only thing that reads like days late.

Recap

Step 14: Where we started, where we ended Before / after

On the left, the fine came from D, F, x and r, and the numbers had no names at all. You had to run the math in your head to learn what any of it meant. On the right, the same math reads as the library's rules. The loan period, the grace period, both rates and the cap each have a name at the top.

Step 15: When to reach for it Takeaways

Rename as soon as you catch yourself reading the body of a function to learn what one of its names means. Leave a short name alone when its scope is tiny, like i in a three-line loop, because everyone already reads it as the index. You'll spot the smell in single letters, names like data or flag, bare numbers, and comments that explain what a variable holds.