[brailleblaster] Implementing options in Java

  • From: "Susan Jolly" <easjolly@xxxxxxxxxxxxx>
  • To: <brailleblaster@xxxxxxxxxxxxx>
  • Date: Thu, 3 Jan 2013 19:38:46 -0700

I noticed that there has been a discussion of semantic actions and of various ways to get BB to perform different functions in different situations so wanted to point out some features of Java that might be useful.


There is no need to use reflection or other complex mechanisms to convert user input options expressed as strings for internal use. One easy way to do this is to match an enum to be used as an internal flag to the specified user input via hash search as shown in following based on an example from the book "Effective Java." Note that, as shown here, the user input can be whatever is desired. It does not have to be the string representation of the name of the enum since it can also be a field of that enum.

enum Days{
MON ("Monday" ),
TUES ("Tuesday" );
private static final Map(String, Days> stringToEnum
= new HashMap<String, Days>();
static {
for (Days day : values()}
  stringToEnum.put( day.userName, day );}
String userName;
Days( String userName ){
this.userName = userName;
}
public static Days fromString( String input ){
return stringToEnum.get( input)
}
}

A similar method can be used to match user input (or other information) directly to actions explictly associated with enums. This approach could avoid a later need for switch statements that use the enum.

enum Days{
MON ("Monday", Monday.INSTANCE ),
TUES ("Tuesday", Tuesday.INSTANCE );
private static final Map(String, Days> stringToEnum
= new HashMap<String, Days>();
static {
for (Days day : values()}
  stringToEnum.put( day.userName, day );}
String userName;
Action action;
Days( String userName, Action action ){
this.userName = userName;
this.action = userAction;
}
public static Action fromString( String input ){
return stringToEnum.get( input ).action
}
}
Here the assumption is that the different classes that perform the desired actions all implement a common interface such as the following.
Interface Action{
void action( Document doc );
}
class Monday implements Action{
public static final Monday INSTANCE = new Monday();
private Monday();
void action( Document doc ){ //do stuff}
}
class Tuesday implements Action{
static final Tuesday INSTANCE = new Tuesday();
private Tuesday();
void action( Document doc )){//do stuff}
}

}

According to the book just mentioned, "An instance of a class that exports exactly one such method [a method that perform operations on other objects passed explicitly to the method] is effectively a pointer to that method." These instances are called "function objects" and play a similar role as do function pointers in other languages.

Please feel free to ask questions.
Sincerely, Susan Jolly


Other related posts: