WEB4J - Minimalist Java Web Application Framework

Class for constants

Creating a class whose sole job is to define widely-used constants is simple.

Example


package hirondelle.web4j.util;

/**
* Collected constants of general utility.
*
*<P>All members of this class are immutable. 
*
* <P>(This is an example of 
* <a href='http://www.javapractices.com/Topic2.cjp'>class for constants</a>.)
*/
public final class Consts  {

  /** Opposite of {@link #FAILS}.  */
  public static final boolean PASSES = true;
  /** Opposite of {@link #PASSES}.  */
  public static final boolean FAILS = false;
  
  /** Opposite of {@link #FAILURE}.  */
  public static final boolean SUCCESS = true;
  /** Opposite of {@link #SUCCESS}.  */
  public static final boolean FAILURE = false;

  /** 
  * Useful for {@link String} operations, which return an index of <tt>-1</tt> when 
  * an item is not found. 
  */
  public static final int NOT_FOUND = -1;
  
  /** System property - <tt>line.separator</tt>*/
  public static final String NEW_LINE = System.getProperty("line.separator");
  /** System property - <tt>file.separator</tt>*/
  public static final String FILE_SEPARATOR = System.getProperty("file.separator");
  /** System property - <tt>path.separator</tt>*/
  public static final String PATH_SEPARATOR = System.getProperty("path.separator");
  
  public static final String EMPTY_STRING = "";
  public static final String SPACE = " ";
  public static final String TAB = "\t";
  public static final String SINGLE_QUOTE = "'";
  public static final String PERIOD = ".";
  public static final String DOUBLE_QUOTE = "\"";

  // PRIVATE //

  /**
  * The caller references the constants using <tt>Consts.EMPTY_STRING</tt>, 
  * and so on. Thus, the caller should be prevented from constructing objects of 
  * this class, by declaring this private constructor. 
  */
  private Consts(){
    //this prevents even the native class from 
    //calling this ctor as well :
    throw new AssertionError();
  }
} 

The caller refers to these constants using static references, such as Consts.EMPTY_STRING, Consts.SUCCESS, and so on. Since the caller will never need to create a Consts object, a private constructor is used to enforce that policy. The members of such a constants class are excellent candidates for a static import.

It is also possible to use an interface to bring constants into scope. Many argue strongly that such a practice is a strange use of interfaces, which are intended to state the services provided by a class.

See Also :
Interface for constants
Private constructor
Use static imports rarely
Would you use this technique?
Yes   No   Undecided   
Add your comment to this Topic :

© 2008 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual code snippets can be used under this license - Last updated on September 6, 2008.
Over 98,000 visits last month - Built with WEB4J.
- In Memoriam : Bill Dirani -