- 37. Do not shadow or obscure identifiers in subscopes
- 38. Do not declare more than one variable per declaration
- 39. Use meaningful symbolic constants to represent literal values in program logic
- 40. Properly encode relationships in constant definitions
- 41. Return an empty array or collection instead of a null value for methods that return an array or collection
- 42. Use exceptions only for exceptional conditions
- 43. Use a try-with-resources statement to safely handle closeable resources
- 44. Do not use assertions to verify the absence of runtime errors
- 45. Use the same type for the second and third operands in conditional expressions
- 46. Do not serialize direct handles to system resources
- 47. Prefer using iterators over enumerations
- 48. Do not use direct buffers for short-lived, infrequently used objects
- 49. Remove short-lived objects from long-lived container objects
40. Properly encode relationships in constant definitions
The definitions of constant expressions should be related exactly when the values they express are also related.
Noncompliant Code Example
In this noncompliant code example, OUT_STR_LEN must always be exactly two greater than IN_STR_LEN. These definitions fail to reflect this requirement:
public static final int IN_STR_LEN = 18; public static final int OUT_STR_LEN = 20;
Compliant Solution
In this compliant solution, the relationship between the two values is represented in the definitions:
public static final int IN_STR_LEN = 18; public static final int OUT_STR_LEN = IN_STR_LEN + 2;
Noncompliant Code Example
In this noncompliant code example, there appears to be an underlying relationship between the two constants where none exists:
public static final int VOTING_AGE = 18; public static final int ALCOHOL_AGE = VOTING_AGE + 3;
A programmer performing routine maintenance may modify the definition for VOTING_AGE, but fail to recognize the resulting change in the definition for ALCOHOL_AGE.
Compliant Solution
In this compliant solution, the definitions reflect the independence of the two constants:
public static final int VOTING_AGE = 18; public static final int ALCOHOL_AGE = 21;
Bibliography
[JLS 2013] |
§4.12.4, “final Variables” |