Java Reference
In-Depth Information
Prior to JDK 5, the commandId variable in the DvdCommand class would probably have been constants,
of the form:
public final static int FIND = 0;
public final static int RENT = 1;
public final static int RETURN = 2;
There are many problems with doing this, though, including the possibility that someone might directly
set the commandId variable to an integer value that is not supported, or they might do something illogical
with the constants (such as try to add them). Furthermore, we cannot enumerate over the number of modes,
and if we tried to print the value of the commandId variable, a number would be returned—we would have
to look up this number in the documentation or in the source code to determine what the number really
means.
JDK 5 provides us with a simpler way of defining these constants: using an enum. The SocketCommand
enum is defined as
package sampleproject.gui;
public enum SocketCommand {
UNSPECIFIED, /* indicate that the command object has not been set */
FIND, /* request will be performing a Find action */
RENT, /* renting a DVD */
RETURN, /* returning a DVD */
MODIFY, /* updating status of a DVD */
ADD, /* creating a new DVD record */
REMOVE, /* delete a DVD record */
GET_DVD, /* retrieve a single DVD from database */
GET_DVDS, /* retrieve multiple DVDs from database */
RESERVE,
RELEASE
}
Now any variable of type SocketCommand can only contain one of these listed options—no other
options are possible.
We also have the benefit that anytime we print (or log) the contents of the commandSocket variable,
the string UNSPECIFIED , FIND , RENT , RETURN , MODIFY , ADD , REMOVE , GET_DVD , GET_DVDS , RESERVE ,or
RELEASE will be printed (or logged)—it will be instantly clear from looking at the output what the variable
was set to.
There are many more benefits of using enums. We recommend you read the release notes related to
enums available at http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html for
more information.
Search WWH ::




Custom Search