-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathNoConstantsOnly.qhelp
More file actions
65 lines (48 loc) · 1.88 KB
/
NoConstantsOnly.qhelp
File metadata and controls
65 lines (48 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Definitions of constants (meaning static, final fields) should be
placed in an appropriate class where they belong logically.
However, it is usually bad practice to implement an interface (or extend an abstract class)
only to put a number of constant definitions into scope.</p>
</overview>
<recommendation>
<p>
The preferred way of putting the constant definitions into scope is to use the
<code>import static</code> directive, which allows a compilation unit
to put any visible static members from other classes into scope.
</p>
<p>This issue is discussed in [Bloch]:</p>
<blockquote><p>
That a class uses some constants internally is an implementation detail.
Implementing a constant interface causes this implementation detail to
leak into the classes exported API. It is of no consequence to the
users of a class that the class implements a constant interface. In
fact, it may even confuse them. Worse, it represents a commitment: if
in a future release the class is modified so that it no longer needs
to use the constants, it still must implement the interface to ensure
binary compatibility.
</p>
</blockquote>
<p>To prevent this pollution of a class's binary interface, it
is best to move the constant definitions to whatever concrete class
uses them most frequently. Users of the definitions could use <code>import static</code>
to access the relevant fields.</p>
</recommendation>
<example>
<p>In the following example, the interface <code>MathConstants</code> has been defined only to hold
a constant.</p>
<sample src="NoConstantsOnly.java" />
<p>Instead, the constant should be moved to the <code>Circle</code> class or another class
that uses the constant frequently.</p>
</example>
<references>
<li>
J. Bloch, <em>Effective Java (second edition)</em>,
Item 19.
Addison-Wesley, 2008.
</li>
</references>
</qhelp>