I'm currently reading Clean Code by Robert C Martin. Here are some of my takeaways, chapter by chapter.
This chapter is all about naming things. I can identify with the challenges and complexities of naming things, and also the hesitance to rename something when we feel its name isn't meaningful or accurate.
Probably my biggest takeaway from this chapter was:
The length of a name should correspond to the size of its scope.
- Page 22
In essence, this chapter says:
- Be accurate and explicit.
- Use tools that make it easy to change names.
- Longer, more descriptive names are usually better, unless
- They contain redundant information.
- Solution or Problem domain names are appropriate given the consumers of our code and its concepts.
- The name of a function, variable or class should answer all of the big questions:
- Why does it exist?
- What does it do?
- How is it used?
function calculateCartItemTotal(item: CartItem): number function calculateCartTotal(items: CartItem): number
- Don't use words with specific meanings to mean something else.
- Beware of using names which vary in small ways.
- Using inconsistent / incorrect spelling is disinformation.
- If names must be different, then they should also mean something different.
- Number series aren't dis-informative, they're non-informative:
a1, a2, a3 ... aN
- Don't use noise words:
ProductData, they mean the same thing.
- Type information does NOT belong in variable names.
/* Don't encode type info in variable names */ const nameString = 'name'; const totalFloat = 85.99; const quantityInteger = 2; /* Don't use similar names for different things. */ function parseIn(a, b) function parseOut(a, b) /* Use explicit names that clearly indicate purpose, intention and usage. */ function parseInputItemsToJson(inputItems, itemsJson) function parseOutputItemsJson(itemsJson, outputContent)
- It's much easier to find
MAX_USERS_ALLOWEDthan it is to find the number
- The letter
eis a terrible name for a variable because it's the most common letter in the english language:
- Single letter variables can only be used locally inside very small methods.
- There's enough encodings to deal with already.
- IDEs are able to extract information about a reference's type without encoding it in its name.
- They're also great at auto completion, so it's better to use a longer name using clear, plain language.
- Examples of encodings to avoid:
- Type encodings:
- Member prefix:
- Type encodings:
- Avoid cultural references
- Don't use slang or colloquialisms.
- Don't make names clever.
- Say what you mean, mean what you say.
- Pick one word per concept and don't use puns.
- Use solution domain names because other engineers will be able to infer their meaning.
- Use problem domain names as non-technical stakeholders will be able to infer their meaning.