java magic value

1. What is magic value

Magic value, also known as magic value or magic number, usually refers to a number that appears inexplicably when writing code. The meaning of the value cannot be directly judged. It must be understood through contextual analysis of the code, which seriously reduces the readability of the code. In addition to numbers, constant strings used as key values ​​in code are also considered magic values. Although their meanings are clearer than values, irregularities still arise.

if( flag = 5 ){
	a = 2;
}

It will not report an error when it is running, but it is difficult to judge what it represents when reading the code

2. The influence of magic value

  • The readability of the code is reduced.
  • The use of numerical values ​​is not standardized, and the use of multiple places is not uniform. The workload of modification is heavy and it is easy to miss.
  • When the constant string is used as the key, the spelling is wrong, and the key value has no corresponding value, resulting in data exception or cache failure

3. Solutions

1. Define static constants

Values ​​used in the current class or inside methods can avoid magic values ​​by defining static constants.

public final static Integer ENABLE=0;
public final static Integer DISABLE=1;

2. Defined in the interface

Defined in the interface, the implementation class that inherits this interface can use these constants

public interface UserService{
    public final static Integer ENABLE=0;
    public final static Integer DISABLE=1;
}

3. Use enumeration

@Getter
@AllArgsConstructor
public enum DemoEnums {

    ENABLE(0, "开启"),
    DISABLE(1, "关闭");

    /**
     * 状态值
     */
    private final Integer code;
    /**
     * 状态名
     */
    private final String name;
}

use

user.setStatus(DemoEnums.ENABLE.value())

Guess you like

Origin blog.csdn.net/cang_ling/article/details/131667758