Constant interface

From CSSEMediaWiki
Revision as of 01:53, 19 July 2009 by JaninaVoigt (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The Constant interface anti pattern occurs when an interface is used to define constants rather than methods. When a class implements that interface, it then gets access to those constants.

This is an inappropriate way of using an interface since constants are an implementation detail. Interfaces are usually used to define contracts by specifying method signatures.

Example

Imagine we are writing a program that needs to use a lot of mathematical constants such as pi and e and for some reason we want to redefine those constants rather than using the ones provided by library classes.

We may make an interface called constants and put the constant definitions in this interface. When we want to use the constants in a class, we simply make the class implement this interface.

Instead, we could have defined the constants in the class that needs to use them or we could have used static imports (since Java 5). Static imports allow us to import constants defined in another file. For example, to import the constant Constants.PI, we use the import statement import static Constants.PI.

Liabilities

  • An instance of the interface has no practical use since it only contains constants and no methods.
  • It can be hard to find where the constants have been declared.
  • This use of interfaces can be confusing because most people will assume that an interface specifies some sort of contract rather than just defining constants.
Personal tools