Constant Interface - Alternatives

Alternatives

Many of the pitfalls of the anti-pattern can be avoided by converting the constants interface to a proper class with no instances:

public final class Constants { private Constants { // restrict instantiation } public static final double PI = 3.14159; public static final double PLANCK_CONSTANT = 6.62606896e-34; }

This still leaves the original intent of the pattern mostly un-addressed (i.e. there is no syntax for accessing the constants unqualified). However, since Java 5, consider using static import to achieve the same goal:

import static Constants.PLANCK_CONSTANT; import static Constants.PI; public class Calculations { public double getReducedPlanckConstant { return PLANCK_CONSTANT / (2 * PI); } }

To varying degrees, the issues listed above have now been addressed:

  1. Because static members can be imported specifically, the class namespace need not be polluted with all members of the constants interface.
  2. Run-time and compile-time semantics are more closely aligned when using static imports instead of constants interfaces.
  3. The compiled code has one less binary compatibility constraint (that "class Calculations implements Constants").
  4. Because static imports apply only to the current file (and not the whole class hierarchy) it is easier to discover where each static member is declared.
  5. There is less need to declare variables of the constants interface type, and it is potentially clearer that no concrete instances actually exist.

Note however, the changes do nothing to improve the cohesion of the Constants class, so static imports should not be considered to be a panacea.

Read more about this topic:  Constant Interface

Famous quotes containing the word alternatives:

    Clearly, society has a tremendous stake in insisting on a woman’s natural fitness for the career of mother: the alternatives are all too expensive.
    Ann Oakley (b. 1944)

    The last alternatives they face
    Of face, without the life to save,
    Being from all salvation weaned
    A stag charged both at heel and head:
    Who would come back is turned a fiend
    Instructed by the fiery dead.
    Allen Tate (1899–1979)

    The literal alternatives to [abortion] are suicide, motherhood, and, some would add, madness. Consequently, there is some confusion, discomfort, and cynicism greeting efforts to “find” or “emphasize” or “identify” alternatives to abortion.
    Connie J. Downey (b. 1934)