Chapter 3 - Names That Can't Be Misconstructed

Published:

Actively scrutinise your names by asking yourself, “What other meanings could someone interpret from this name?”

Example: Filter()

Filter is an ambiguous word, it can either mean “to pick out”, or “to remove”. select() is better in the former case and exclude() in the latter.

Example: Clip(text, length)

Clip() clips the contents of the paragraph. But its unclear whether it:

  • removes length from the end of the paragraph
  • truncates to a maximum length.

Second option is more likely, so a better name could be Truncate(). But the parameter length could also be made better by changing it to max_length.

And futher, what is max_length representing? Bytes? Words? Characters? It could be changed to max_chars to make it really clear.

Prefer min and max for (Inclusive) Limits

The clearest way to name a limit is to put max_ or min_ in front of the thing being limited.

For example, limiting shopping cart to 10 items, use the variable MAX_ITEMS_IN_CART = 10, instead of CART_ITEM_LIMIT = 10, as its not clear as the latter is an inclusive or exclusive limit.

Prefer first and last for Inclusive Ranges

first and last are really clear keywords - its obvious that last will be included in the selection.

Naming Booleans

Example:

bool read_password = true

So which of the following is meant?

  • we need to read the password
  • the password has already been read

In the first case, a better name would be need_password. And in the second: user_is_authenticated.

In general, words like is, can, has, and should can make boolean variables more clear.

Also, its good to avoid negated terms in a name, instead of:

bool disable_ssl = false

Its easier to read & more compact to write:

bool use_ssl = true

Matching Expectations of Users

Users have preconceived ideas on what certain names mean, while you might have something completely different in mind.

Example: get*()

Its easy to think that methods starting with get are lightweight accessors.

However, it might be that the method is actually doing an expensive operation, pulling in lots of data & working out the result on the fly. This is dangerous, as programmers can be calling this method unaware of the cost implications. In such cases, the word compute should be used instead of get.

Example: list::size()

In C++, list.size() is an O(n) operation. An unaware programmer might be expecting it to be an O(1) operation.

To avoid such misunderstanding, size() should better be named countSize() or countElements(), to indicate that this is a compute-intensive operation.

Summary

The best names are the ones that can’t be easily misinterpreted. Many words are ambiguous, such as filter, length and limit.

A good approach is to play the role of the devil’s advocate and imagine how the names might be misunderstood. The best names are resistant to misinterpretation.