Use enums to restrict arguments

Type-safe enumerations are useful for constraining arguments which must take a small set of values, such as a boolean or a restricted set of Strings or ints.

As an example from the servlet API, recall this method for the creation of an HttpSession:

aRequest.getSession(true);

Any reader who is not familiar with the specification of this method will be forced to look up the meaning of the boolean literal before they can understand the method call. An alternative style is to define a well-named variable which explains the intent:

boolean CREATE_IF_ABSENT = true;
aRequest.getSession(CREATE_IF_ABSENT);

However, the caller is not compelled to use such a style. If a type-safe enumeration is used for the argument, then the caller is indeed forced into a style which has greater clarity.

aRequest.getSession(HttpServletRequest.CreateIfAbsent.YES);

Here, CreateIfAbsent would be a static nested type-safe enumeration with two elements, YES and NO. This style has these advantages:

This style can be a bit verbose. It might be one of those rare occasions where a static import of the enum class is appropriate, to avoid using fully qualified names.

Example 1

Here's a stub class illustrating an alternate form of createSession:


import javax.servlet.http.HttpSession;

/** Clarify method call with enum argument.  */
public final class HttpRequestWithEnum {

  /**
  * Example of calling the method with an enum arg.
  */
  public static void main(String... aArgs){
     HttpRequestWithEnum request = new HttpRequestWithEnum();
     HttpSession session = request.createSession(CreateIfAbsent.YES);
  }
  
  public HttpSession createSession(CreateIfAbsent aCreateIfNeeded){
    return null; //stubbed out
  }
  
  /** The enumeration itself.  */
  public enum CreateIfAbsent {YES, NO};
}
 

Example 2

Here's a second example that uses an enum instead of a boolean literal.


import java.io.*;

public final class LawnMower {

  enum Power{ON, OFF};

  void switchPower(Power aPower){
     if (Power.ON == aPower){ 
       //elided..
     }
     else if (Power.OFF == aPower){
       //elided..
     }
  }

  //..elided

  public static void main(String... args){
    LawnMower mower = new LawnMower();
    //this is clearer than passing a boolean literal:
    mower.switchPower(Power.ON);
  }

} 



See Also :
Type-Safe Enumerations
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -