Re: Swing is dead! Long live Swing.
Wanja Gayk wrote:
markspace wrote:
... For situations where I might be tempted to just use strings,
I try to substitute enums. For example, instead of
bind( someComponent, "event-name" );
I'd use this:
bind( someComponent, Events.NAME );
It provides automatic syntax checking, and is much easier to refactor if
names need to be changed or moved around later.
Any thoughts on this idea?
I think the same way.
I'm even going further and strongly propose preferring Enums to boolean
parameters and this is why:
http://brixomatic.wordpress.com/2010/02/24/boolean-harmful/
+1
This might irritate those who already find Java verbose, since 'String's are
more compact to declare, but type safety and refactorability [sic] is a payoff
in many situations.
I'm even worse, because I pump a "friendly" string representation into the enum.
<http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#toString()>
??An enum type should override this method when a more "programmer-friendly"
string form exists.??
Necessitating a corresponding 'public static E fromString(String rep)'.
'fromString()' compares 'toString()' strings first; if those fail it delegates
to 'valueOf()'.
<sscce source="eegee/Essential.java">
package eegee;
/**
* Essential {@code enum} implementation with "friendly" representation.
*/
public enum Essential
{
FOO("foo"),
BAR("bar"),
FANCY("fancy form"),
ANOMALY("useful to hold log or error messages"),
;
private static final long serialVersionUID = 1L;
private final String representation;
/**
* Constructor setting the friendly representation.
* @param rep String friendly representation of constant.
*/
private Essential(String rep)
{
this.representation = rep;
assert this.representation != null;
}
@Override
public final String toString()
{
return representation;
}
/**
* Look up enum constant from String representation.
* @param rep String representation of enum constant.
* @return Essential constant matching the representation.
*/
public static Essential fromString(String rep)
{
if (rep == null)
{
return null;
}
for (Essential value : values())
{
if (rep.equals(value.toString()))
{
return value;
}
}
return valueOf(rep);
}
}
</sscce>
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg