Java Reference
In-Depth Information
Such declarations are not required to be on a separate line, and the explanatory com-
ment may be omitted.
Bibliography
[Conventions 2009]
§6.1, “Number Per Line”
[ESA 2005]
Rule 9, Put Single Variable Definitions in Separate Lines
[JLS 2013]
§4.3.2, “The class Object”
§6.1, “Declarations”
§8.3, “Field Declarations”
§9.3, “Field (Constant) Declarations”
§14.4, “Local Variable Declaration Statements”
39. Use meaningful symbolic constants to represent literal values in
program logic
Java supports the use of various types of literals, such as integers (5, 2), floating-point
numbers (2.5, 6.022e+23), characters ( 'a' , '\n' ), Booleans ( true , false ), and strings
( "Hello\n" ). Extensive use of literals in a program can lead to two problems. First, the
meaning of the literal is often obscured or unclear from the context. Second, changing a
frequentlyusedliteral requiressearchingtheentireprogramsourceforthatliteral anddis-
tinguishing the uses that must be modified from those that should remain unmodified.
Avoidtheseproblemsbydeclaringclassvariables withmeaningfully namedconstants,
setting their values to the desired literals, and referencing the constants instead of the lit-
eralsthroughouttheprogram.Thisapproachclearlyindicatesthemeaningorintendeduse
of each literal. Furthermore, should the constant require modification, the change is lim-
ited to the declaration; searching the code is unnecessary.
Constants should be declared as static and final . However, constants should not be
declared public and final if their values might change (see Guideline 31 , “ Do not apply
public final to constants whose value might change in later releases , ” for more details).
For example,
Search WWH ::




Custom Search