Meaningful Names over Comments
Throughout this course you will work on Shelfwise, a small online bookshop: customers, books, orders, payments and shipping. Its oldest file contains d = 14 and a function called calc(o, f). Every new developer asks the same question: what are d, o and f? Code is read far more often than it is written, and names are the first thing every reader meets.
The rule
If a name needs a comment, rename it instead.
A comment that explains what a variable holds is a sign that the name failed. Put the meaning into the name, and the comment has nothing left to say.
# Before
d = 14 # days a customer has to ask for a refund
def calc(o, f): # o = order, f = True if member discount applies
...
# After
REFUND_WINDOW_DAYS = 14
def order_total(order, apply_member_discount):
...A few habits make names work:
- Say what it is for, not how it is stored.
unpaid_orders, notlist2. - Put units in the name when a number has one:
timeout_seconds,weight_grams. - Functions are verbs (
send_receipt), classes are nouns (Invoice), booleans read as questions (is_paid,can_refund). - Name magic numbers.
14means nothing;REFUND_WINDOW_DAYSmeans everything.
How long should a name be? Match it to its reach. A variable that lives for two lines can be short: in for line in order.lines:, line is perfect, and an i counting through a tiny loop is fine. A name that travels across files, such as a module constant or a public method, needs to be fully descriptive, because its readers will meet it far from where it was defined, with no surrounding code to explain it.
Comments still have a job: explaining why. "Tax is added before the discount because our accountant requires it" is knowledge no name can carry.
The shortcut
Read the line aloud to someone who has never seen the codebase. Wherever you have to add "…which means…", that is the name to fix.
Read it aloud
if o.s == 2 and d > 14:reads as "if o dot s equals two and d is more than fourteen", which means nothing.
The trap is the long, vague name. data_manager_helper is longer than d but no clearer. Length is not the goal; meaning is.
Drills
Answer fast — trust the rule.
Which name should replace t in t = 30 # seconds before an idle checkout expires?
Which comment is worth keeping?
A function returns whether a customer may pay later. Which name fits best?
A class holds the lines, total and due date of a bill sent to a customer. Best name?
Remember
- If a name needs a comment, rename it; comments are for why, not what.
- Read the line aloud: every "which means" marks a name to fix.
- Trap: long, vague names such as
data_manager_helperare no better than one letter.
