Good Naming — Clean Code

Measure a name by how many things the reader has to remember. The checkout function calc(k, v), with t and the magic numbers (numbers with no explanation)…

In the last lesson, the checkout function calc(k, v) made the reader answer six questions before daring to change a single line. Almost all of them were questions about names. The names of variables and functions are an explanation written inside the code itself, so they go wherever the code goes. A good name answers the reader's question before they even ask it.

A name works like the label on a kitchen jar. You just grab the jar labelled "sugar". You have to open the jar labelled "stuff" or "jar 2" and taste it first. In code, the jar is a variable, and the label is that variable's name. A variable called k, data or temp is like the jar labelled "stuff": you have to read the code to learn what it holds.

Measure a name by what the reader has to remember

Here is the checkout function of Raka's T-Shirt Shop from the previous lesson. Its result is right: Total: $220.50 for 2 plain tees and 1 printed tee with the voucher SAVE10.

function calc(k, v) {
  let t = 0;
  for (let i = 0; i < k.length; i++) {
    t = t + k[i].price * k[i].qty;
  }
  if (v === 'SAVE10') t = t - t * 0.1;
  if (t < 200) t = t + 15;
  return 'Total: $' + t.toFixed(2);
}

How to measure a name: count how many things the reader has to keep in mind while reading. Every name that doesn't explain itself adds one thing. So does every magic number (a number in code with no explanation).

Name now What the reader has to remember A name that explains itself
calc calculates the order total, returns text calculateTotal
k the cart, holding items with price and qty cart
v the voucher code voucherCode
t the total, updated as it goes total
0.1 the SAVE10 voucher discount VOUCHER_DISCOUNT
200 the free-shipping minimum FREE_SHIPPING_MIN
15 the shipping fee SHIPPING_FEE

Seven things for a 9-line function. With the names in the right column, there is nothing to remember: every name answers its own question. i can stay i, because the loop is only 3 lines long and everyone knows i is an index.

Generic names are as unclear as abbreviations

A generic name fits any value, such as data or temp. It is tempting to replace k with data, v with str and t with temp:

function processData(data, str) {
  let temp = 0;
  // ... exactly the same
}

The code looks tidier, but the reader still has to remember the same seven things. What data does data hold? What text is str? What does temp keep? Generic names like data, info, str, temp, result and processData only state a type (str is short for string) or "something", not the value's role (what it is for in that code). So for a cart, data is no clearer than k. What helps is a name that states the role: cart, voucherCode, total.

Practical rules

Rename: the name changes, the result doesn't

Renaming is the safest refactor there is, as long as every use gets renamed. Say only the first line changes:

function calculateTotal(cart, voucherCode) {
  let t = 0;
  for (let i = 0; i < k.length; i++) { // k is still the old name

When it runs, the result is an error:

Uncaught ReferenceError: k is not defined

The parameter is called cart now, so the name k no longer exists. Use your editor's Rename Symbol (F2 in VS Code): every use of the name changes at the same time. After a rename, run the code again and make sure the output is still Total: $220.50.

The exercise: the active user list

In the exercise, the code is different, but the problem is the same: it has the names d, arr, fn, x and r. Rename them, and leave the logic as it is:

Old name What it holds Example new name
d today's date today
arr the user list users
fn the function that keeps active users filterActiveUsers (this exact name is required)
x one user user
r the filtered result activeUsers

What gets graded:

⚠️ Half-done renames and names that lie

TL;DR: Measure a name by how many things the reader has to remember. The checkout function calc(k, v), with t and the magic numbers (numbers with no explanation) 0.1, 200 and 15, asks for seven. calculateTotal(cart, voucherCode) with named constants asks for none. Generic names (data, str, temp) are as unclear as abbreviations, because they only state a type, not the value's role. Use verbs for functions, nouns for variables, and is/has/can at the start of boolean names (true/false values). Match a name's length to its reach (the part of the code that uses it), keep types out of names, say what you get (getUsersByActiveStatus(), remainingDaysUntilDeadline), and use one consistent language. When you rename, rename every use at the same time, then check the output is the same.

⚡ Measure a name by what the reader must remember

Guess first: the checkout function calc(k, v) is only 9 lines long. Inside it are the variable t and the numbers 0.1, 200 and 15, with no explanation. How many things does its reader have to remember?

Seven: calc, k, v, t, 0.1, 200 and 15. Once it's calculateTotal(cart, voucherCode) with named constants, none.

Meaning: Every name that doesn't explain itself, and every number with no name (a magic number), adds one thing to remember. The variable i in that function's loop can stay i: the loop is only 3 lines long, and everyone knows i is an index.

⚡ Generic names are just as unclear

Write:

function processData(data, str) {
  let temp = 0;
  // ... exactly the same
}

Meaning: This is the checkout function calc(k, v) after its name became processData, k became data, v became str and t became temp. It looks tidy, but the reader still has to guess. data, str and temp are generic names: they only state a type or "something", not the value's role. What helps is a name that states the role: cart, voucherCode, total.

⚡ Drop filler words

Meaning: Filler words such as Data, Info, Value, Number and temporary rarely add meaning. For the days left until a deadline, remainingDaysUntilDeadline is clearer than temporaryDeadlineCalcValue. Verbs for functions, nouns for variables, and is/has/can at the start of boolean names (true/false values), such as isMember.

⚡ Rename every use

Write:

function calculateTotal(cart, voucherCode) {
  let t = 0;
  for (let i = 0; i < k.length; i++) { // k is still the old name
Guess first: in the checkout function, calc(k, v) was renamed to calculateTotal(cart, voucherCode), but only on the first line. What happens when the code runs?

An error: Uncaught ReferenceError: k is not defined. The parameter is called cart now, so the name k no longer exists.

Meaning: A rename is safe only when every use is renamed too. Use your editor's Rename Symbol (F2 in VS Code): every use changes at the same time. Then run the code again and make sure the output is still Total: $220.50.

What you will learn