Enums: Properties vs. Methods
All,
I am just musing about the pros and cons of using boolean properties
in enum classes vs. custom methods. So far I found
pro Properties:
- less classes
- when adding enum values to an enum you cannot forget to define
properties
pro Methods:
- smaller memory footprint per instance
Considering that there are always only so many instances it seems the
properties approach wins. It seems, custom methods in enum instances
are most useful if enums do actually do something. Then different
enums can have differing implementations of the method and we have an
instance of Strategy / State pattern.
Do you have more items for the lists? Did I overlook something?
Kind regards
robert
Example
/** We use boolean properties. */
public enum Prop {
A(true, true), B(true, false), C(false, true);
private final boolean a;
private final boolean b;
Prop(boolean a, boolean b) {
this.a = a;
this.b = b;
}
public boolean isA() {
return a;
}
public boolean isB() {
return b;
}
}
/** We use custom methods. */
public enum Meth {
A, B {
@Override
public boolean isB() {
return false;
}
},
C {
@Override
public boolean isA() {
return false;
}
};
public boolean isA() {
return true;
}
public boolean isB() {
return true;
}
}
Full toy class https://gist.github.com/892503#file_prop_vs_meth.java