constant definition


1. [Mandatory] No magic values ​​(i.e. undefined constants) are allowed to appear directly in the code.

Counter example: String key =" Id # taobao _" tradeId;

cache . put(key , value);

2. [Mandatory] When initializing long or Long, you must use uppercase L, not lowercase l. Lowercase is easy to be confused with the number 1, causing misunderstanding.

Explanation: Long a = 2 l; Is it written as a numeric 21 or a Long type 2?

3. [Recommendation] Do not use a The constant class maintains all constants, which should be classified according to constant functions and maintained separately. For example: Cache related constants are placed under the class: CacheConsts; system configuration related constants are placed under the class: ConfigConsts.

Note: For a large and comprehensive constant class, you have to use the search function to locate the modified constant, which is not conducive to understanding and maintenance.

4. [Recommendation] There are five levels of reuse of constants: shared constants across applications, shared constants within applications, shared constants within subprojects, shared constants within packages , and shared constants within classes.

1) Share constants across applications: Place them in a second-party library, usually in the constant directory in client. jar.

2) In-application shared constants: placed in the constant directory in the modules of the library.

Counter example: Easy-to-understand variables must also be uniformly defined as shared constants within the application. The two siege masters defined variables representing "yes" in two classes:

In class A: public static final String YES = " yes " ;

In class B: public static final String YES = " y " ;

A . YES . equals(B . YES), expected to be true, but actually returned false, causing online problems.

3) Shared constants within subprojects: that is, in the constant directory of the current subproject.

4) Shared constants within the package: that is, in a separate constant directory under the current package.

5) Shared constants within the class: defined directly inside the class private static final.

5. [Recommendation] If the variable value only changes within a range, use the Enum class. If there are extended attributes other than names, you mustuse the Enum class. The numbers in the following example are extended information, indicating the day of the week.

##Positive example: public Enum { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5),

SATURDAY( 6 ) , SUNDAY( 7 ); }