The second chapter mainly discusses some minor standards to be followed in naming.
1. Live up to your name
1. The name of a variable, function, or class should answer all the big questions, and if the name needs to be annotated, it’s not worthy of the name
int d; // Elapsed time, in daysCopy the code
The name D says nothing, evoking no sense of the passage of time, let alone in terms of days. The name of the measurement object and measurement unit should be selected
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
Copy the code
2. Code ambiguity: The degree to which context is not clearly represented in the code
A name that reflects the intent makes it easier to understand and modify the code. For example, develop a minesweeper game where you find marked squares on a disk. Each cell is represented by an array whose 0 subscript indicates its state and records whether or not it is marked
public List<int[]> getThem(){
List<int[]> list1 = new ArrayList<int[]>();
for(int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
Copy the code
It’s hard to see what the code is doing, but the problem is the ambiguity of the code: the degree to which the context is not explicitly represented in the code.
You need to know the answers to questions like the following when reading the code above:
- What types of things are in theList?
- What is the significance of theList’s sub-zero entry?
- What does the value of 4 mean?
- How do I use the returned list?
The answer should be in the code. If a subzero entry is a status value and 4 means “marked”, using meaningful names,
The improvements are as follows:
public List<int[]> getFlaggedCells(){
List<int[]> flaggedCells = new ArrayList<int[]>();
for(int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
Copy the code
So instead of representing cells in an array, one class is written to represent each cell. The class includes an isFlagged function that can easily tell what is happening by changing the name.
2. Avoid misdirection
1. Programmers must avoid leaving false clues that hide the true meaning of the code. Avoid using words that are contrary to their original meaning
Do not refer to a group of accounts as accountList unless it is truly a List. It’s better to use accountGroup, bunchOfAccounts, or even Accounts.
Beware of names that are less different.
Such as XYZControllerForEfficientHandlingOfStrings and XYZControllerForEfficientStorageOfStrings.
3. Spelling the same concept in the same way is information, and inconsistencies are misleading.
Note the use of lowercase I and uppercase O for variable names that look like “one” and “zero”
int a = 1;
if(O == 1){
a = O1;
}else{
1 = O1;
}
Copy the code
3. Make meaningful distinctions
1. Names must be different, so their meanings should be different. Avoid adding numbers or nonsense distinctions.
If a programmer writes code just to satisfy the needs of a compiler or interpreter, it creates trouble. If you change the name of one of two different things in the same scope because they don’t have the same name, it’s not enough to add a series of numbers.
Examples of errors:
public static void copyChars(char[] a1, char[] a2){ for(int i = 0; i < a1.length; i++){ a2[i] = a1[i]; }}Copy the code
If the parameter names were changed to source and destination, this would look much more presentable.
2. Nonsense is another meaningless distinction.
Suppose you have a Product class. If you also have a ProductInfo or ProductData class, the names are different but the meanings are the same
getActiveAccount(); getActiveAccounts(); getActiveAccountInfo(); MoneyAmount and Money customerInfo and Customer accountData and Account theMessage and messageCopy the code
3. It’s fine to use prefixes like a and the, as long as they show a meaningful distinction.
4. Nonsense is redundant.
The word Variable should never appear in a Variable name, and the word Table should never appear in a Table name
4. Use pronounceable names
Programming is a social activity, and identifier names need to be readable.
For dates: Use generationTimestamp instead of Genymdhms.Copy the code
5. Use searchable names
1. The problem with single-letter names and numeric constants is that they are hard to find in a large text
A long name is better than a short one, and a search for a name is better than a name written in your own code. The length of the name should correspond to its scope size
for (int j = 0; j < 34; j++){
s += (t[j]*4)/5;
}
int readDaysPerIdealDay = 4;
final int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++){
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = realTaskDays / WORK_DAYS_PER_WEEK;
sum += realTaskWeeks;
}
Copy the code
6. Avoid coding
1. Codifying a type or scope into a name increases the decoding burden in vain
phoneNumber phoneString; // When the type changes, the name does not change!Copy the code
2. There is no need to prefix member variables with m_. Classes and functions should be made small enough to eliminate the need for member prefixes.
public class Part{ private String m_dsc; // The Textual description void setName(String name){ m_dsc = name; } } public class Part{ private description; void setDescription(String description){ this.description = description; }}Copy the code
People quickly learn to ignore prefixes or suffixes and see only the meaningful parts of a name. The more code you read, the less prefix you see. Eventually the prefix became an unattractive waste.
3. Do not use leading letters for plain interfaces
ShapeFactory IShapeFactory instead of ShapeFactory ShapeFactoryImpCopy the code
7. Avoid mental mapping
1. The reader should not be able to translate your name in their head into a name they are familiar with. Single-letter variable names are a problem
Let’s say you use r for a loop variable name. But others think it is a URL without a host name or schema. So single-letter names are not a good choice
2. Understanding, clarity is king for professional programmers
8. The name of the class
1. Class and object names should be nouns or noun phrases, and class names should not be verbs
Customer, WikiPage, Account, and AddressParser, avoid class names like Manager, Processor, Data, or Info. Class names should not be verbs.
9. The method name
1. Method names should be verbs or phrasal verbs.
Such as postPayment, deletePage, or Save. Property accessors, modifiers, and assertions should be named according to their values and prefixed with GET, SET, and IS according to the Javabean standard
2. Consider making the corresponding constructor private to enforce this naming technique
When you overload the constructor, use a static factory method name that describes the parameters. For example, Complex fulcrumPoint = complex.fromRealNumber (23.0); Generally better than Complex fulcrumPoint =new Complex(23.0);Copy the code
10. Don’t be cute
1. Mean it, mean it. Don’t use slang ==
For example, who knows what the HolyHandGrenada function is? Yes, it’s a clever name, but DeleteItems might be a better name.
11. There is a word for each concept
For example, using ==fetch==, ==retrieve==, and ==get== to name the same method in multiple classes (just using those words individually) would take a lot of time to navigate through the various headers and the code that precedes them.
For example, use one of controller, Manager, or driver.
12. No puns
1. Avoid using the same word for different purposes
For example, if you write a method that adds a number to a collection using add, the name of the method should not be add. Insert or Append are more appropriate.
2. Try to write code that is easy to understand, so that it can be read by others without being exhaustively researched
13. Use solution domain names
1. Use computer science terms, algorithm names, schema names, mathematical terms
14. Use names derived from the area in question
1. If the work at hand cannot be named in terms familiar to the programmer, use a name derived from the problem domain
2. One of the jobs of good programmers and designers is to separate the concepts of solution domains from problem domains
15. Add meaningful context
1. You need to place names with well-named classes, functions, or namespaces to give context to the reader.
In the following code, the variables number, VERB, and pluralModifier must be passed through the function to infer their meanings:
private void printGuessStatistics(char candidate, int count){
String number;
String verb;
String pluralModifier;
if (count == 0){
number = "no";
verb = "are";
pluralModifier = "s";
} else if (count == 1) {
number = "l";
verb = "is";
pluralModifier = "";
} else {
number = Integer.toString(count);
verb = "are";
pluralModifier = "s";
}
String guessMessage = String.format(
"There %s %s %s%s", verb, number, candidate, pluralModifier);
print(guessMessage);
}
Copy the code
To improve the
To decompose this function, create a class called GuessStatisticsMessage so that the variable is, by definition, part of GuessStatisticsMessage. The enhanced context allows algorithms to become cleaner by decomposing into smaller functions.
public class GuessStatisticsMessage{ private String number; private String verb; private String pluralModifier; public String make(char candidate, int count){ createPluralDependentMessageParts(count); return String.format( "There %s %s %s%s", verb, number, candidate, pluralModifier); } private void createPluralDependentMessageParts(int count){ if (count == 0){ threAreNoLetters(); } else if (count == 1){ thereIsOneLetter(); } else { threAreManyLetters(count); } } private void thereAreManyLetters(int count){ number = Integer.toString(count); verb = "are"; pluralModifier = "s"; } private void thereIsOneLetter() { number = "l"; verb = "is"; pluralModifier = ""; } private void thereAreNoLetters(){ number = "no"; verb = "are"; pluralModifier = "s"; }}Copy the code
2. If not, prefix your name as a last resort
16. Don’t add useless contexts
1. Short names are better than long ones, as long as they are clear enough.
For example, prefix the class name with the abbreviation of the project name.
Both accountAddress and customerAddress are good names for entities of the Address class, but not so good for class names.
Address is a good class name. If a MAC address, port address, and Web address are to be distinguished, PostalAddress, MAC address, and URL are used. Such names are more precise, and precision is the point of naming.
17. Last word
The hardest part about choosing a good name is that it requires good descriptive skills and a shared cultural background. Use the above rules and come on, you can do it!
18. References
Zhuanlan.zhihu.com/p/37639722 www.cnblogs.com/stoneniqiu/… www.jianshu.com/p/c44eca6ad…
Pay attention to the public account “Programmer interview”
Reply to “interview” to get interview package!!
This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!
1. Computer network —- Three times shake hands four times wave hands
2. Dream come true —– Project self-introduction
Here are the design patterns you asked for
4. Shocked! Check out this programmer interview manual!!
5. Teach you the interview “Profile” word for word
6. Nearly 30 interviews shared