Naming is a problem

· Code Quality


Naming is harder than writing code because the name has to survive longer than
the code. The function might change. The name has to explain what it does when
someone reads it a year from now.

The name that lies

def process(data)
  parse(data)
  validate(data)
  save(data)
end

What does this do? No idea. process could mean anything. Six months from now,
someone reading this will spend twenty minutes figuring out what it does.

Better: import_and_validate_user_data or parse_and_persist_csv or whatever
it actually does.

The name that tells a story

def apply_late_fee(invoice)
  invoice.amount += 10
  invoice.save
end

The name tells a story: this function applies a fee. The code confirms it: the
amount increases and the change is persisted.

The name and the code agree, and someone reading the name knows what to expect.

The name that hides the cost

def get_user(id)
  User.find(id)  # database call, 50ms
end

The name says get. The reader expects a cache lookup. The code does a
database call. The name is not lying but it is misleading.

Better: fetch_user_from_database or load_user or something that hints at
the cost.

The rule that works

A name should answer the question: “What happens if I call this?” If the name
does not answer that question, the name is wrong.

The name that is technically right but still wrong

def handle_response(response)
  # 200 lines of logic
end

Technically correct. But the word handle is so broad that it is empty. It does
not answer the question at all.

The names in every codebase

These names are not bad because they are short. They are bad because they do
not answer the question.

What I learned

Spend more time on the name than the code. A name that is right makes the code
obvious. Code that is obvious is easier to maintain.

The name that costs you five minutes to think of saves someone an hour of
confusion later.

naming clarity intent
last updated: