20 Tips for Better Naming(提高命名能力的20個建議)

20 Tips for Better Naming(提高命名能力的20個建議)

Names are everywhere in code. As programmers, we name our classes, our variables, our functions, our arguments, our namespaces and more. Given that we do so much of it, we should spend time making sure we do it well. Here are 20 tips to help you improve.

1. Use intention revealing names:

A name should tell you what it does, why it exists, and how it is used. Choosing names that reveal intent makes it much easier to understand and change code.

 
int d; // elapsed time in days
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;

In the snippet above, we can only tell what the variable d refers to from the comment. A reader would have to search for it's instantiation to get any clue as to it's meaning. In contrast, if we were to use one of the other names for this variable, a reader should be able to intuit what this variable refers to instantly.

2. Don’t be afraid to spend time choosing a name:

You shouldn't feel guilty about taking your time and trying several different names until you find one that you feel is adequately descriptive. Everyone who ends up reading your code in the future (including you) will benefit from this initial outlay of time. In addition, coming up with a descriptive name will often help clarify the design of the module in your mind. Good naming takes time but in the long term, will save more than it takes.

3. Refactoring names:

If you think of a better name later in the development process, don’t hesitate to change it. Modern IDE’s make refactoring names incredibly easy. It is not uncommon to change a name only for a favourable restructuring of the code to become apparent.

4. Avoid noise words in your names:

Noise words like Manager, Processor, Data, or Info and are synonyms for “I don’t know what to call this”. If you find yourself wanting to use one of these words it may be that the thing you are trying to name is doing too much.

5. Be wary of hard to name classes/functions:

A hard to name class or function is a possible code smell. If you are finding it difficult to give a class or function an expressive name this could be a sign that:

  • the offending code is doing too much.
  • the offending code is not doing enough.
  • you do not understand the domain well enough and need to get more information before continuing.

6. Class names:

Classes should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. When using inheritance superclasses should have short and punchy names. Subclasses should have longer names containing adjectives that describe how this class differs from it’s superclass e.g. SavingsAccount derives from Account.

7. Variable names:

Variables often hold instances of classes so they should be nouns too. They are often derived from the name of the class that they refer to. Boolean variables should be written as predicates e.g. isEmpty or isTerminated so that they read well in if statements.

8. Method names:

Methods should have verb or verb phrase names like postPayment(), deletePage() or save(). Accessors and mutators should be prefixed with get and set respectively. Methods that return a boolean should be prepended with ‘is’ such as isPostable() so that they read well in if statements.

9. Scope size to variable name length:

For variables the length of the name should correspond to the size of it’s scope. If the variable is used in only a very short scope then the length of the variable name should be very short. Conversely, if the variable is within scope for a long time, the name of the variable should be more descriptive and so the name should be longer.

10. Scope size to method/class name length:

For methods and classes the length of the name should inversely correspond to the size of it’s scope. For public methods, shorter names are usually better as they will be called many times. Private methods will only be called within the scope of the class and so longer names are preferred that will act as documentation. The exception to this rule are derived class names. The more derived a class, the more adjectives are applied to the base class name and the longer it will be.

11. Pick one word per concept:

Pick one word for one abstract concept and stick to it. For example it’s confusing to have get(),fetch() and retrieve() as equivalent methods of different classes. A consistent lexicon is an important tool for programmers that must work with your code.

12. Avoid using the same term for two disparate concepts:

If you follow the one word per concept rule then you will end up with many classes that have the same method names. This is fine as long as the parameter lists and return values of the various methods are semantically equivalent. Where problems will occur is if you use the same term for two disparate concepts.

For example, we could use an add() method in multiple classes to denote the creation of a new value by adding or concatenating two existing values. If we then introduce an add method to a class in which it is used to add a single parameter into a collection this will cause problems as the semantics are different. A better term for this new method would be insert().

13. Use solution domain names:

The code we write will be viewed by other programmers. Since this is the case it is beneficial to use technical terms where appropriate such as algorithm names, pattern names and maths terms given that these should evoke the correct concepts in the minds of the reader.

14. Use problem domain names:

When there is no technical name for a concept then it is wise to use a name from the problem domain. This will provide the option for future readers of your code to consult a domain expert if they are unsure what something in the code is doing.

15. Add meaningful context:

Most names are not meaningful in and of themselves and would need to be placed within a context (class/function/namespace) for a reader to understand what they refer to. In some cases it may be necessary to prefix names to add some context. For example, if we have a number of variables that are used to represent an address firstName, lastName, street, houseNumber, city, state and zip. If you just saw the state variable it would be hard to automatically infer what it was referring to, a better solution would be to encapsulate the variables in an Address class.

16. Don’t add gratuitous context:

Short names are generally better than longer ones, so long as it is clear, don’t add context to a name that does not need it. Names should not be prefixed with unnecessary information that can be inferred from the class/package/namespace that the name is within.

17. Avoid encodings:

Given the power of modern day IDE’s, we do not need to encode type or scope information into the names of our variables or classes. This includes not appending I to interfaces, the users of our code do not need to know that their classes are being passed an interface. If you have to use encoding then it is better to encode the implementation than it is to encode the interface.

18. Avoid disinformation:

Do not leave false clues that misinform the reader as to the meaning of the code. If you have a variable named accountList that actually holds an array this may lead to false conclusions. A name should say what it means, and mean what it says.

19. Use pronounceable names:

Programming can be a social activity, using unpronounceable names hampers our ability to discuss the code that we are working on with others.

20. Use searchable names:

Using short generic names hampers our ability to search for things within our codebase. This is important for manoeuvring around the code and in our ability to refactor.

If you have any other tips please leave a comment below.


分享到:


相關文章: