14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Constant interface 100<br />

Constant interface<br />

In the Java programming language, the constant interface pattern describes the use of an interface solely to define<br />

constants, and having classes implement that interface in order to achieve convenient syntactic access to those<br />

constants. However, since the usage of constants is an implementation detail, it is considered inappropriate to define<br />

an interface for this purpose. [1] [2] In general, collecting system constants into classes independent of behaviour,<br />

might create a poor object-oriented design, because it is often a sign of low cohesion. It is for these reasons that<br />

implementing constants interfaces is considered to be an anti-pattern.<br />

Use of this anti-pattern has a few other downsides:<br />

1. It pollutes the class namespace with read-only variables that may not be of use.<br />

2. Contrary to the compile-time tactical utility of implementing a constants interface, the incidental run-time<br />

artifacts have little practical purpose (cf. marker interfaces which also have no methods but are useful at<br />

run-time).<br />

3. If binary code compatibility is required in future releases, the constants interface must remain forever an interface<br />

(it cannot be converted into a class), even though it has not been used as an interface in the conventional sense.<br />

4. Without an IDE that resolves where the constant are coming from, tracking it back to its containing class or<br />

interface can be time consuming.<br />

5. A variable (representing an instance) of the interface is syntactically no more useful than the interface name itself<br />

(since it has no methods).<br />

Example<br />

public interface Constants {<br />

}<br />

public static final double PI = 3.14159;<br />

public static final double PLANCK_CONSTANT = 6.62606896e-34;<br />

public class Calculations implements Constants {<br />

}<br />

public double getReducedPlanckConstant() {<br />

}<br />

Alternatives<br />

return PLANCK_CONSTANT / (2 * PI);<br />

Many of the pitfalls of the anti-pattern can be avoided by converting the constants interface to a proper class with no<br />

instances:<br />

public final class Constants {<br />

private Constants() {<br />

}<br />

// restrict instantiation<br />

public static final double PI = 3.14159;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!