Skip to the workspace
Pebellslearn by building
Clean Code Principles  ›  Lesson

Meaningful Names over Comments

Meaningful names over comments 12 minA well-chosen name tells the reader what a value or function is for, so comments are saved for explaining why.

software design architecture / Meaningful Names over Comments

Explore each scene at your own pace.

01 · The rule

The rule

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, not list2.
  • 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. 14 means nothing; REFUND_WINDOW_DAYS means 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.