Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Problem of 0.
In daily code writing, the following statements are often used in judgment conditions:
if(!"1".equals(MapUtils.getString(user, "role"))){
...
}else{... }Copy the code
This statement is normal when the program runs, but it violates the development specification. If alibaba Java development specification plug-in is used in IDEA, there will be a prompt: “magic value [“1″]”, magic value [“role”].
Click on the details of the specification alert to see that no mana values (i.e., undefined constants) are allowed to appear directly in the code.
1. Mana
1.1 Magic value concept
Magic value, also known as magic value, magic number, usually refers to the inexplicable number in the code writing, can not directly determine the meaning of the value represents, must be linked to the code context analysis can be understood, which seriously reduces the readability of the code.
In addition to numbers, constant strings that are key values in code are also considered magic values, which can cause irregularities even though they are more explicit than numbers.
1.2 Why does mana appear
In the process of data processing, in order to make full use of the storage performance of the machine, the database storage tends to use more simple numerical values to represent the meaning of complex nouns, such as the use of 1, 2, 3, 4 and other numerical values to represent the state information, 0, 1 to represent false and true.
Because the database stores numerical data, the back-end code also needs to use numerical values to verify the data when interacting with the data, resulting in the existence of a large number of [magic values] in the back-end code.
This way of writing does not produce any execution errors and the code is concise, but the code meaning is very unintuitive and the cost of review and maintenance is huge.
1.3 Potential damage of mana
In addition to unintuitive code reading, mana can cause the following problems:
- The use of numerical values is not standardized, the use of multiple places is not uniform, the workload is heavy and easy to miss when modifying
- Numerical use error, the program does not generate exceptions, but business logic data problems
- When the constant string is used as the key, the spelling is incorrect and the key value does not correspond to the value. As a result, data is abnormal or the cache fails to match
2. Mana solution
2.1 Static constant method
Values that are used only in the current class or within a method can be avoided by defining static constants. Replace magic values in code with static constants as follows:
public static final String ADMIN_ROLE = "1";
public static final String _NAME_ = "name";
if(! ADMIN_ROLE.equals(MapUtils.getString(user, _NAME_))){ ... }else{... }Copy the code
Static constants are defined with all letters of the convention name capitalized to indicate that the identifier is invariant, and the Ali Baba specification in IDEA does not raise questions when used this way.
2.2 Enumerate class methods
Enumeration classes are another, more formal way to eliminate magic values. You need to define an enumeration class and define properties and constructors for the class. Enumeration classes can constrain the definition of static constants, provide a uniform format for static constant values, and are widely used in uniform exceptions and other things.
public enum CommonCodeEnum{
// 'status information (1- unapproved, 2- approved, 3- Approved, 4- rejected)',
STATUS_INFO_1(1."Not reviewed"),
STATUS_INFO_2(2."Reviewed"),
STATUS_INFO_3(3."Approved"),
STATUS_INFO_4(4."Audit void");
private int code;
private String caption;
ComnCodeEnum(int code, String caption) {
this.code = code;
this.caption = caption;
}
public int code(a) {
return code;
}
public String caption(a){
returncaption; }}Copy the code
Once the enumeration class information is defined, we can use enumeration values instead of magic values in our code
if(CommonCodeEnum.STATUS_INFO_1.code().equals(user.getStatus())){
...
}else{... }Copy the code
2.3 The necessity of eliminating mana
When we use static constants or enumerated classes instead of magic values in our code, we find that in most places the code is not simpler, but more complex, and the way we used it is the same, so it raises the question: A lot of repetitive constant extraction definitions are desirable, but is it necessary to define static constants or enumerated classes that use strings and values only once in a class or locally in a method?
- This question can be said to be a matter of opinion, code specification is very necessary for the large project with a large number of participants and refined modules, because everyone has their own development style, different personal styles mixed into a project, resulting in that is called sibuxiang.
- Of course, for personal development of small projects, as long as the correctness of the business logic data is not so important to the development specification, but I have to say that the development of following the specification in the later maintenance is called a smooth!
3. Summary
I learned on the job and improved myself constantly. By solving the problem of standard reminder of magic value in the code, I found:
- During development, we should constantly improve our code specification awareness. Most of the bugs in the project are caused by non-standard code
- Make good use of various code specification tools, such as Alibaba Java development specification plug-in, code quality scanning tools, etc., to find and solve problems, learn and accumulate knowledge