<!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>
