Software design philosophy: Chapter XIV choose a good name

Variables, methods, and other entities, select the name of one of the aspects of software design is the most underrated. Good name is a form of the document: they make the code easier to understand. They reduce the need for other documents, and error detection easier. In contrast, poor name choice will increase the complexity of the code, which could lead to ambiguity and misunderstanding bug. Select the name is an example of the principle of increasing complexity. Select a variable for a specific common name, but not the best possible name may not generate the overall complexity of the system too much. However, the software system has thousands of variables, complexity and management will have a significant impact for all of these to choose the right name.

14.1 Example: a bad name will cause an error

Sometimes, even a bad name variable will cause serious consequences. The most challenging I have restored the error is due to the wrong choice of name. In the late 1980s and early 1990s, I and my graduate student created a distributed operating system, called Sprite. In a way, we note that the data files are sometimes lost: a data block suddenly becomes all 0, even if the file is not modified. This problem occurs infrequently, it is particularly difficult to trace them. Some graduate trying to find this bug, but they can not make progress and eventually gave up. However, I believe that any unresolved bug is unbearable personal insults, so I decided to track it.

Although it took six months, but I finally found and fixed the bug. This problem is actually quite simple (most of the bug, too, as long as you clear them). The file system code blocks of variable names used for two different purposes. In some cases, the block is a physical block number on the disk; in other cases, blocks referenced in the document logical block number. Unfortunately, there is a variable block contains a logical block number in the code, but in a context where the physical block number in the incidental use of it; a result, a disk block is irrelevant 0 covered.

Bug tracking process, several people, including me, read error codes, but we never noticed this problem. When we see a variable block as a physical block number, we instinctively think it really holds the physical block number. Psychological barrier I spent a long period of time to test and eventually found a particular statement in error must have occurred, and then I was able to cross this name caused, and check its value in the end where they come from. If different variable names for different types of blocks (e.g. fileBlock and diskBlock), an error is less likely to occur, the programmer should not be used know fileBlock in this case.

Unfortunately, most developers do not spend a lot of time thinking about names. They tend to use the first name comes to mind, as long as it named it something very close. For example, the block with the logical blocks and physical blocks in the file on the disk closely match; This is certainly not a terrible name. Nevertheless, it still leads to a lot of time overhead to keep track of a subtle bug. Therefore, you should not be satisfied with those "pretty close" to the name. Spend some extra time to choose a good name, these names must be accurate, clear and intuitive. Extra attention will soon be rewarded over time, you'll soon learn to choose a good name.

14.2 create an image

When you select a name, the goal is to create an image on the essence of things named in the mind of the reader. A good name to convey a lot of information about what the underlying entity is equally important is that it is not information. When considering a particular name, ask yourself: "If someone saw this name alone, did not see its statement, document or any code that uses the name, they can guess the name refers to what is right ? "there is no other name can make you a clearer picture of the situation?" and, of course, information about a person's name can provide is limited; if the name contains than two or three words, it would be very awkward. Therefore, our challenge is to find the words to describe the most important aspects of this entity.

Is the name of an abstract form: they provide a simplified way to think about a more complex underlying entity. As with other forms of abstraction, the best names are those names will focus on the most important aspects underlying entity, and ignore less important details.

14.3 to be exact name

Good name has two attributes: accuracy and consistency. Let's start from the precision. Name the most common problem is too general or vague; therefore, the reader is difficult to know what is meant by that name; readers might think the name refers to the reality of different things, just above the same block bug. Consider the following method declaration:

"Count" is the word too broad: what counts? If you see someone call this method, they are less likely to know what it has done, unless they read its documentation. GetActiveIndexlets or numIndexlets such as more accurate name would be better: With one of these names, the reader may not be able to guess the contents of the document to see the method returns.

/**

 * Returns the total number of indexlets this object is managing.

 */

int IndexletManager::getCount() {...}

The following are examples of some of the other less accurate name, variety of items taken from students:

  • Building GUI text editor project with the name of x and y to represent the location of the file in characters. These names are too common. They could mean many things; for example, they also coordinate of the character on the screen can be represented (in pixels). X name alone see people are less likely to think that it refers to the location of the character in a line of text. If you use such a name charIndex and lineIndex, the code will be clearer, these names reflect the particular abstract code implementation.

  • Another project editor contains the following code:
// Blink state: true when cursor visible.

private boolean blinkStatus = true;

blinkStatus the name does not convey enough information. "Status" is the word for a Boolean value is too vague: it does not give any clue about the true or false value meaning. "Blink" the word is very vague, because it does not indicate what is blink. The following is a better choice:


// Controls cursor blinking: true means the cursor is visible,

// false means the cursor is not displayed.

private boolean cursorVisible = true;

cursorVisible name conveys more information; for example, it allows the reader to guess the meaning of true value (as a general rule, the name of Boolean variables should always predicate). The name is no longer "blink" of the word, so if readers want to know why the cursor is not always visible, it is necessary to consult the documentation; this information is less important.

  • Project implementation consensus agreement contains the following code:
// Value representing that the server has not voted (yet) for

// anyone for the current election term.

private static final String VOTED_FOR_SENTINEL_VALUE = "null";

The name of the value that it is special, but it did not specify any special meaning yes. More specific names such as not_yet_ will be better.

  • Using a variable named result in no return value of the method. This name has multiple issues. First, it will result in a misleading that it would be the return value of the method. Secondly, it basically does not provide any information about the actual content it holds, except that it is other than a calculated value. Name should provide information about the actual results, such as mergedLine or totalChars. In the method does have a return value, use the name of the result is reasonable. This name is still somewhat generic, but the reader can see the method documentation for its meaning, to understand the value of the final will be the return value is helpful.

Danger signals: fuzzy name

If a variable or method name broad enough, you can reference a lot of different things, then it can not deliver too much information to the developers, the underlying entity is more likely to be misused.

As with all rules, select the exact name of the rule with some exceptions. For example, as long as the cycle span only a few lines of code, you can use a generic name i and j such as variable loop iteration. If you can see a whole range of variables, it can be seen that the meaning of the variable from the code, and therefore need not be very long name. For example, consider the following code:

for  (i = 0; i < numLines; i++){      
    ...
}

As is clear from this code, i is used to traverse each line of an entity. If the loop is too long, you can not see it all at once, or if it is difficult to find out the meaning of the iteration variable from the code, then the more descriptive name should be used.

Name also may be too specific, for example, in this statement, a way to remove a range of text:

void delete(Range selection) {
    ...
}

Select the parameter name too specific, because it shows that the deleted text is always selected in the user interface. However, you can call this method on any range of text selected or unselected. Thus, the parameter name should be more general, such as range.

If you find it difficult to find a precise, intuitive, not too long name for a particular variable, then this is a dangerous signal. This indicates that the variable might not have a clear definition or purpose. When this happens, consider alternative factors. For example, you may be trying to use a single variable to represent multiple things; if so, will represent separated into multiple variables may cause more simple definition of each variable. Select the good name of the design process can be improved by identifying weaknesses.

Danger signals: it is difficult to select the name

If the variable or method is difficult to create a clear image of the underlying object to find a simple name, then this implies that the underlying object could not have a clean design.

14.4 maintain consistency

The second important attribute of a good name is consistency. In any program, there are some variables used repeatedly. For example, the file system repeatedly block number. For these common usage, choose a name for this purpose, and use the same name anywhere. For example, the file system may always use fileBlock to save the index file blocks. Consistent naming reduces the cognitive burden on its way to reuse public class is very similar: immediately make assumptions Once the reader to see the name in a context, they can reuse their knowledge and see things in different contexts.

Consistency has three requirements: First, always use the generic name for a given purpose; second, not the common name used on any matter related to a specific purpose; third, to ensure that the purpose of the narrow enough, all have names the variables have the same behavior. This third requirement is violated at the beginning of this chapter file system errors. File system uses variable block has two different behaviors (block file and disk blocks); this leads to erroneous assumptions about the meaning of variables, leading to a bug.

Sometimes you'll need more variables to represent the same thing. For example, the data file copy method requires two block numbers, one for source, one for the destination. When this happens, the public name for each variable, but may add a prefix to distinguish, such as srcFileBlock and dstFileBlock.

Circulation is consistent naming another area can provide help. If you use i and j names like loop variable, i is always used in the outermost loop, and use j in a nested loop. This allows the reader to see immediately (safely) assume that what happened given the code name.

14.5 different perspectives: Go style guide

Not everyone will agree with my views on the naming. Some developers think of Go language name should be very short, usually only one character. Go in the debate about the name of the selected speech, Andrew Gerrand pointed out that "long name to cover up the role of the code." He gives this code sample, which uses single letter variable names:

func RuneCount(b []byte) int {
       i, n := 0, 0
       for i < len(b) {
             if b[i] < RuneSelf {
                   i++
             } else {
                   _, size := DecodeRune(b[i:])
                   i += size
             }
             n++
       }
       return n
}

And that it more readable than the following version, use the following version of a longer name:

func RuneCount(buffer []byte) int {
       index, count := 0, 0
       for index < len(buffer) {
             if buffer[index] < RuneSelf {
                   index++
             } else {
                   _, size := DecodeRune(buffer[index:])
                   index += size
             }
             count++
       }
       return count
}

For me personally, I do not think the second version is more difficult to read than the first version. If anything, then the name count for behavioral variables provides a better clue than n. In the first version, I finally read through the code, trying to figure out the meaning of n, whereas in the second version, I feel no need to do so. However, if you always use the n throughout the system to reference count (rather than anything else), then other developers may clear the short name.

Go culture encourages the use of several different things the same short name; ch represent characters or channel, d represents the data, differences or distance, and so on. For me, an ambiguous name like this could cause confusion and error, as the block as an example.

Overall, I think the readability must be determined by the reader, not the author . If you write code that has a short variable names, and read it found it easy to understand, then it is possible. If you start getting too mysterious code on your complaint, you should consider using a longer name (search on the Web "go language short name" will identify a few such complaints). Similarly, if I started receiving complaints that the longer variable names to make my code difficult to read, then I would consider using shorter variable names.

I agree Gerrand made a comment: "The greater the distance between a statement and its use of the name, the name should be longer." Discussed on the use of loop variables i and j is an example of this rule.

14.6 Conclusion

Carefully chosen names will help make the code more clear. When a person first encountered this variable, their first guess its behavior is correct. Select the name is a good example of investment mentality discussed in Chapter 3: in advance if you spend a little extra time to choose a good name, future work on the code will be easier. In addition, you will be less likely to introduce bug. To develop a naming skills are also an investment. When you first decided not to settle for mediocrity in the name, you may find it frustrating and time-consuming to come up with a good name. However, as you gain more experience, you will find it easier. Eventually, you will find, choose a good name is almost no extra time, so you can get these benefits almost free.

Guess you like

Origin www.cnblogs.com/peida/p/12095125.html