Re: Using enums to avoid using switch/if
Lew quoted or indirectly quoted someone who said :
I need a mechanism to map string to enum.
Why do you not attribute the quote to the one who actually wrote it?
Roedy Green wrote:
see the built-in valueOf function. I often override it to make it
case insensitive and allow aliases.
I doubt that very much. Static methods cannot be overridden.
While there is some value in hiding the 'valueOf' method, I prefer to
use a differently-named method for the same purpose. I am loathe to
(apparently) change the behavior of such a standard, language-defined
method as 'Enum.valueOf'. Instead I use a static 'fromString()'
method to be the companion for 'toString'.
The 'Enum' Javadocs suggest that '[a]n enum type should override
[toString] when a more "programmer-friendly" string form exists.' I
find it mnemonic and symmetrical to go from "programmer-friendly"
string form to enum constant with 'fromString'. This also preserves
the semantics of 'valueOf' as documented in the JLS. Furthermore, I
use 'valueOf' as the fallback if 'fromString' is otherwise unable to
locate the enum constant.
My enum template is:
/* ${name}.java
*/
package ${package};
/**
* ${name}.
*/
public enum ${name}
{
private final String repr; // "friendly" representation
/**
* Constructor.
* @param rep String representation of enum value.
*/
${name}( String rep )
{
this.repr = rep;
}
@Override
public final String toString()
{
return this.repr;
}
/**
* Look up enum constant from String representation.
* @param rep String representation of enum value.
* @return ${name} constant matching the representation.
*/
public static ${name} fromString( final String rep )
{
if ( rep == null )
{
return null;
}
for ( ${name} val : values() )
{
if ( rep.equals( val.toString() ) )
{
return val;
}
}
return valueOf( rep );
}
}
--
Lew