This is a quick review of the main points in the “Clean Code” chapter on names. Clean Code is available as a video or book.
Communication
- Communication is important when naming variables, methods and classes
- Names should not require comments to explain their intent
- Collaborators should not need to read a lot of code to understand a name’s meaning
- What a name says it is/does should reflect what it actually is/does
- Make names readable/pronounceable
Parts of speech
The idea is that code should read like “well written prose”, using the appropriate parts of speech.
- Booleans should be predicates (e.g. isEmpty)
- Classes and variables should be nouns (e.g. BankAccount, savings)
- Methods should be verbs (e.g. getName()), unless the method returns a boolean, in which case it should be a predicate
- Enums should be adjectives (e.g. GREEN)
Scope Length Rule
- Variables: longer scope, longer descriptive names: shorter scope, shorter names
- Functions & Classes: longer scope/public/called often: short, convenient names
shorter scope/private/infrequently called: long, detailed names - Derived/Sub- classes: longer names as they become more descriptive/less abstract