Episode 02 – Name

Clean Code

Episode 02

The second episode talks about how to name variable, classes and function. Most of the ideas are coming from Tim Ottinger’s Rules for Variable and Class Naming paper.

  • Reveal the intent
    • variable should described itself.
  • Described the problem
    • If you need to read the code to understand the name, then the name failed its purpose
    • Name is a tool to communicate intent and this is its first priority when naming
  • Avoid disinformation
    • Name should say what it means and mean what it says
  • Pronounceable name
    • Name that can be pronounced, can be communicate effectively. On the other hand, name can’t be pronounced, cannot be communicate effectively.
  • Avoid encoding
    • Using encoding distract the communication of the name and obscure the readability of the code.
  • Part of speech
    • Variable and class should be noun or noun phrase (e.g. date, account, address … etc.)
    • Method and function should be verb (e.g. setDate, getName, changeNameTo … etc.)
    • Boolean variable and function that returns a boolean should be a predicate (e.g. isSet, isLate … etc.)
    • Enum should be adjectives.
    • Ignore noise word like manager, data, info, processor that does not add meaning to the name.
    • Use get for accessor (getName … etc)
  • Scope length rule
    • The longer the scope of a variable, the longer the name should be
    • It is ok to use one alphabet to represent a variable if the scope is very short (e.g. i for index in a compact for-loop)
    • The longer the scope of a function or a class, the shorter the name should be
    • Public function and classes should have short name because it will be call from many places and it should be convenience to do so.
    • Derived class often add adjective in front of parent class and get longer (e.g. Account, savingAccount … etc.)
Advertisements