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:
- the method is forced to be more intelligible at the point of call
- the need to look up the specification is greatly reduced
- it serves as a reminder to those who are already familiar with the specification
- it has compile-time safety (not an issue with a boolean argument, but important if the argument is a String or int)
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); } }