Constant interface
JaninaVoigt (Talk | contribs) (Created page about constant interface anti pattern) |
m (Reverted edits by Ebybymic (Talk); changed back to last version by Bertrand Roussel) |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 14: | Line 14: | ||
*It can be hard to find where the constants have been declared. | *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. | *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. | ||
+ | |||
+ | {{Design Anti-patterns}} | ||
+ | [[Category: Anti-Patterns]] |
Latest revision as of 03:03, 25 November 2010
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.
Design anti-patterns | |
---|---|
Anemic Domain Model | BaseBean | Call super | Circle-ellipse problem | Circular dependency |