1. [Mandatory] Magic values, except for predefined, are forbidden in coding.
Counter example: String key = “Id#taobao_” + tradeId;
2. [Mandatory] ‘L’ instead of ‘l’ should be used for long or Long variable because ‘l’ is easily to be regarded as number 1 in mistake.
Counter example:
Long a = 2l
, it is hard to tell whether it is number 21 or Long 2.
3. [Recommended] Constants should be placed in different constant classes based on their functions. For example, cache related constants could be put in CacheConsts
while configuration related constants could be kept in ConfigConsts
.
Note: It is difficult to find one constant in one big complete constant class.
4. [Recommended] Constants can be shared in the following 5 different layers: shared in multiple applications; shared inside an application; shared in a sub-project; shared in a package; shared in a class.
1) Shared in multiple applications: keep in a library, under constant
directory in client.jar;
2) Shared in an application: keep in shared modules within the application, under constant
directory;
Counter example: Obvious variable names should also be defined as common shared constants in an application. The following definitions caused an exception in the production environment: it returns false, but is expected to return true for A.YES.equals(B.YES)
.
Definition in Class A: public static final String YES = "yes";
Definition in Class B: public static final String YES = "y";
3) Shared in a sub-project: placed under constant
directory in the current project;
4) Shared in a package: placed under constant
directory in current package;
5) Shared in a class: defined as ‘private static final’ inside class.
5. [Recommended] Use an enumeration class if values lie in a fixed range or if the variable has attributes. The following example shows that extra information (which day it is) can be included in enumeration:
Positive example: public Enum{ MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7);}