Names and Comments

CleanCode

Next part of my notes from Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin.

clean_code_names

Names

What makes a good name of a class, method, variable, etc.? Every name created in the code should be:

  • meaningful and reveal coder’s intentions
    The name of a variable, function or class should answer  questions such as why it exists, what it does, how it is used. If a name requires a comment, then the name does not reveal its intent. This name tells nothing about the variable:
int d; //the duration time in days

The following name will be much better:

int elapsedTimeInDays;
  • searchable, easy to locate across a body of text
    If you try to search for int a variable, you will get hundreds of meaningless results.
  • distinctly different from other used names
    Do not crate very similar names that are used together. The code will be hard to read.
  • pronounceable
    Names should be easy to pronounce. We not only read the code, but also talk about it.Moreover:
  • there should be one name per concept
    For example words give, fetch, retrieve all mean the same. Choose one of them to make your code consistent.
  • avoid encodings
    Prefixes or Hungarian Notation (for example: bool bBusy, char chInitial) are not a good idea. A variable that has its type changed, but accidentally not its name will be misleading.
  • single-letter variable names are only okay for  loop counters if their scope is very small
  • avoid names like Manager, Processor, etc., as the name of a class
    If you feel like giving your class such a name, it probably does more than one thing (see: Single Responsibility Principle) and should be split into several classes.

Comments

  • Good code does not need too much comments and explanations.
    Comments are a necessary evil. Code should speak for itself without the need of comments.
  • It’s easy to change your code but forget about the comments.
  • Sometimes comments are useful.
    For example legal comments, information about consequences, explanation of intent, TODO comments.
  • Never comment out code. Remove it if it is not necessary. You can always find it in the repository.

References

Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin

http://www.itiseezee.com/?p=83

http://www.itiseezee.com/?s=comments

Leave a comment