What is magic value

"Magic Value" refers to a constant value that is used directly in code without clear meaning or explanation. These constant values ​​often appear in the code in a hard-coded manner, without providing clear naming or comments to explain their meaning.

Using magic values ​​can cause problems with code readability, maintainability, and understandability. Here are some possible problems with using magic values:

  1. Poor readability: Directly using numeric or string constants as magic values ​​without providing clear naming makes the code difficult to understand and read. Other developers may not immediately understand what these values ​​mean when reading the code.

  2. Poor maintainability: If the magic value needs to be changed, all places in the code that use this value need to be found and modified. Such modifications can easily be missed, causing the code to behave incorrectly.

  3. Poor reusability: If magic values ​​are used in multiple places and no clear naming is provided, it will become difficult to reuse these values ​​in other code. Every time you need to use these values, you need to find and copy the corresponding magic value again.

To avoid problems with magic values, constants or enumerations should be used instead of direct hard-coded values. By giving your constants or enumerations meaningful names, you can make your code clearer and easier to understand. In addition, constants and enumeration values ​​are centrally managed and can be easily modified and reused.

For example, if you have a magic value in your code that represents the day of the week 3, you can replace it with an enumeration type DayOfWeekthat contains explicitly named constant values ​​such as MONDAY, TUESDAYetc.

In summary, magic values ​​are constant values ​​that are used directly in code without clear meaning or explanation. To improve code readability and maintainability, you should avoid using magic values ​​and use constants or enumerations instead, giving them meaningful names.

Guess you like

Origin blog.csdn.net/qq_44543774/article/details/133164396