WEB4J - Minimalist Java Web Application Framework

Interface for constants

It is possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name. This is only a minor advantage.

The static import feature should always be considered as a replacement for this practice.

Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class.

Example


interface OlympicMedal {
  static final String GOLD = "Gold";
  static final String SILVER = "Silver";
  static final String BRONZE = "Bronze";
}
 

Here is an example of using this interface to reference its constants


public class OlympicAthlete implements OlympicMedal {

  public OlympicAthlete( int aId ){
    //..elided
  }

  //..elided

  public void winEvent( ){
    //the athlete gets a gold medal
    //note the reference is not qualified, as
    //in OlympicMedal.GOLD
    fMedal = GOLD;
  }

  // PRIVATE //
  private String fMedal; //possibly null
} 



See Also :
Type-Safe Enumerations
Class for constants
Use static imports rarely
Would you use this technique?
Yes   No   Undecided   
Add your comment to this Topic :

© 2009 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual code snippets can be used under this license - Last updated on January 4, 2009.
Over 100,000 unique IPs last month - Built with WEB4J.
- In Memoriam : Bill Dirani -