Please rethink extended enums inclusion

Tom Hawtin tom.hawtin at oracle.com
Fri Oct 7 05:38:25 PDT 2011


On 07/10/2011 12:34, Jose Antonio Illescas Del Olmo wrote:
> Now we have hundred of enums on our project (finantial application with
> 120.000 lines) an repeat same code on any enum... (*mark as red*)

>      public enum Type {

[...]
>         public void setCode(String code) {
>             this.code = code;

I have to point out that mutable enums, or other statics, is generally a 
*really* bad idea. (Also a non-null check here wouldn't go amiss.)

It seems what we want here is a mutable Map<String,E extends Enum<E>>, 
which is easy enough.

 > **      public static Type fromCode(String code) {

Your inheritance wont work here. not unless you do something really dodgy.

> **      public boolean in(Type... types) {  // IMO all enums must have
> this method
>             if (types == null) return false;
>             for(Type type: types) {
>                if (this == type) return true;
>             }
>             return false;
>         }

     asList(a, b, c).contains(en)

Collection literals would help marginally.

Even if you were going for mutable statics (and I still strongly suggest 
you don't) it doesn't seem a difficult problem, so long as you don't 
require these methods within the enum itself. Just introduce a class 
that contains the mapping, and add an instance to each enum. You may 
need to implement a one-method interface if you want to initialise the 
mappings from MyEnum.values().

Tom



More information about the coin-dev mailing list