In the last article, I shared some practical tips on function naming. Today, we will continue the topic of naming variables.

The following is an outline of the table of contents:

Variable naming style

Two. Variable naming the highest realm

Best practices for variable naming

Please forgive me if there is anything wrong, and welcome criticism and correction.

Please respect the author’s labor achievements, please mark the link of the original text:

https://www.cnblogs.com/dolphin0520/p/10639167.html

Variable naming style

Variable naming styles are usually distinguished by variable types. For example, in the Java language, there are two naming styles based on variable types:

1) Class member variables, local variables

Class member variables and local variables are usually named in a hump style, as follows:

String userName;
Copy the code

2) Static member variables, enumerated values, constants

Static member variables, enumerated values, and constants are usually capitalized and multiple words are underlined, such as:

public static final int MAX_YEARS = 25;
​
// It is recommended that enumeration classes end with Enum
enum ColorEnum {
    RED(0."Red"),
    YELLOW(1."Yellow"),
    GREEN(2."Green"),
    WHITE(3."White"),
    BLACK(4."Black");
    private int code;
    private String name;
​
    Color(int code, String name) {
        this.code = code;
        this.name = name; }}Copy the code

Two. Variable naming the highest realm

In the function naming that we say the highest state of function naming is to see the word as surface, so for variable naming, what is the highest state? I think it is: self-explanatory, code as comment.

Why? Because usually a function will have a comment, even if the name of the function is not good, if the comment is written clearly, it is a way for the maintenance personnel to understand the specific function.

And variable, on the other hand, in a project, the number of variables is far greater than the number of functions, so is unlikely to each variable to write comments, so if a project variable name is bad, so for the follow-up maintenance personnel will be a devastating blow, because each read a variable, may need to go to the meaning of the predictor variable, I don’t think anyone wants to read code like this. Always remember, “Code is written for people, not machines.”

For example, the following code is badly named:

ppn = (cpn > 1)? (cpn -1) : cpn;
npn = (cpn < tpn) ? (cpn + 1) : tpn;
​
p = new Page(ppn, cpn, npn, tpn);Copy the code

In the above code, only the author knows clearly what each variable means.

It is much more readable if you change it to the following, and it is easy to see that it is probably intended to compute paging information:

prePageNum = (curPageNum > 1)? (curPageNum -1) : curPageNum;
nextPageNum = (curPageNum < totalPageNum) ? (curPageNum + 1) : totalPageNum;
​
page = new Page(prePageNum, curPageNum, nextPageNum, totalPageNum);Copy the code

Best practices for variable naming

1) Use nouns or adjectives to name variables

It is generally recommended to use a noun, a combination of names or an adjective for variables, because variables generally describe a thing or a property of a thing, so it is easier to understand using a noun or a combination of nouns, while adjectives are generally used for variables of type bool.

2) Avoid using single-letter variables and try to refine the meanings of variables

In your program, avoid using single-letter variables. The only scenarios where single-letter variables are acceptable are for loops, but using single-letter variables in for-loops is still not recommended (pos and index are much better than I, j, and k for loops).

For example, the following line of code:

double calConeVolume(double b, double d) {
  return Math.PI * b * b * d / 3;
}Copy the code

At first glance, this function argument seems clear, but on closer inspection, what is b? What is d? If I want to use this function, how do I pass it in? Most of you are probably confused, and you have to look at the actual implementation of the function to know that B is the radius of the cone and D is the height of the cone;

So how do you optimize the naming of this code? In fact, it is very simple, slightly refine the variable meaning, let the variable name express the actual intention:

double calConeVolume(double radius, double height) {
  return Math.PI * radius * radius * height / 3;
}Copy the code

3) Use the same words before and after naming variables

In the same project or scenario, the variable naming style should be consistent. For example, total and sum can both mean total, so use either total or sum in all cases where “total” is required.

Keeping the same naming style before and after is the key to ensure good readability of engineering code.

4) Set variables are suffixed by type or complex number S

In Java, there are many collections, such as List, Map, Set, etc., so what is the name of the collection variable?

There are two ways to do this:

  • Use the plural s at the end

List<Student> students = new ArrayList<>();
Copy the code

  • Use the collection type as the suffix

List<Student> studentList = new ArrayList<>();
Copy the code

The above two methods can be used, there is no obvious preference, according to the actual scene. The first method is more concise, and the second method is more discriminative when there are multiple related set variables in the local scope, such as:

List<Student> studentList = new ArrayList<>();
Map<Long, Student> studentMap = Maps.newHashMap();
​
for (Student stu : studentList) {
  studentMap.put(stu.getId, stu);
}Copy the code

My recommendation is to use the plural form if the local scope has only one type of collection; If the local scope has more than one related collection type, the type ending is recommended.

5) Disallow the use of is as a bool prefix

In Java, it is forbidden to use is as a prefix for bool member variables, because it can lead to serialization/unsequence problems. Ali’s Java code specification explicitly states this, so it is best to follow the accepted specification when writing code, otherwise you may one day be broken.

6) Avoid abbreviations

Sometimes, variable names can be a bit long, which can make the code less readable, so it’s often a bad idea to use abbreviations when writing code, unless the abbreviations are common convention abbreviations.

For example, the following name:

int avgStudentAge;
Copy the code

Since avG is known as the abbreviation of Average, it is not a problem to write it this way and will not cause ambiguity.

But the following abbreviations:

res
tmp
cnt
depCopy the code

Is not a good abbreviation, because different people reading may have different interpretations:

Res => Response, resource, result TMP => temporary, template CNT => count, Content, contextCopy the code

Attach some abbreviations commonly known as conventions:

The full name abbreviations
identification id
average avg
maximum max
minimum min
buffer buf
error err
message msg
image img
length len
library lib
password pwd
position pos
data transfer object dto
view object vo

7) Discard flag variables

Some early textbooks in China are full of various flag-style variables, which is a nightmare for large projects, such as:

int flag = getDoctorFlag(doctorId);
if (flag == 1) {
  //....
}Copy the code

Looking at this code, the reader may wonder what the flag variable means. What does flag mean when it is 1? Is it the doctor’s on-duty/on-duty state, or the doctor’s physical state? I guess the reader’s heart is broken.

If optimized to the following form:

DutyStatus doctorDutyStatus = getDoctorDutyStatus(doctorId);
if (doctorDutyStatus == DutyStatus.ONLINE) {
  // ...
}Copy the code

It is much clearer than the above form, and it is easy to see that what is being judged is the doctor’s on-duty/on-duty status.


Blog garden link: https://www.cnblogs.com/dolphin0520/

The public no. :