Refactoring Method 26: replace magic number with symbolic constant (replace the magic number with a literal constant)

Source: Internet
Author: User

 

You have a literal value with a special meaning.Create a constant, name it according to its meaning, and replace the preceding literal value with this constant.

Motivation: In computing science, magic number is one of the undesirable phenomena with a long history. The so-called magic number refers to a number that has a special meaning, but cannot clearly express this meaning. If you need to reference the same logical number in different locations, the magic number will upset you, because once these numbers change, you mustProgramAnd modify them all. Even if you don't need to modify it, you may have to worry about how to accurately point out the purpose of each magic number.

Constants can be declared in many languages. Constants do not cause any performance overhead, but they can be greatly improved.CodeReadability.

Before refactoring this item, you should look for other alternatives. You should observe whether the magic number is used, and then you will often find a better way to use it. If the magic number is a type code, use replace type code with class (replace the type code with class). If the magic number represents the length of an array, when traversing an array, use an array instead. length.

Practice: 1. Declare a constant and set its value to the original magic value.

2Find all reference points of this magic number.

3Check whether the new declared constant can be used to replace the magic number. If possible, replace it with this constant.

4, Compile.

5 compile and test all magic counts after they are replaced. At this time, the entire application runs normally, just as it has not been modified.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.