Simple things should be simple, complex things should be possible.
Alan Kay
I've been working quite a lot in Java. As part of the university course, we work with BT's people and 'bring meaningful innovation'. Because of university policies, we have to work in Java. Every now and again (more often than not actually), I came across painfully annoying constructs which make the code that much harder to read and write. Like today, I had to work with enums. They are really simple in C#:
1 2 3 4 |
public enum LegNo { NO_LEG = -1, LEG_ONE = 1, LEG_TWO = 2 |
Meanwhile the same construct in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public enum LegNo { NO_LEG(-1), LEG_ONE(1), LEG_TWO(2); private int legNo; private static Map<Integer, LegNo> map = new HashMap<Integer, LegNo>(); static { for (LegNo legEnum : LegNo.values()) { map.put(legEnum.legNo, legEnum); } } private LegNo(final int leg) { legNo = leg; } public static LegNo valueOf(int legNo) { return map.get(legNo); } } |
Obviously, enums in Java are far more sophisticated and powerful than in C#:
1) Type safety and value safety.
2) Guaranteed singleton.
3) Ability to define and override methods.
4) Ability to use values in switch statement case statements without qualification.
5) Built-in sequentialization of values via ordinal().
6) Serialization by name not by value, which offers a degree of future-proofing.
7) EnumSet and EnumMap classes.
EPJ on StackOverflow
Nevertheless, I am struggling to appreciate those benefits especially as they come at a heavy price of readability and maintainability of the code. For example, more often than not, Singletons are considered an anti-pattern. At the moment I am silently praying that this may be one of the remnants of the old Java - but who knows.