Syntactic Diabetes

The following Java code is legal, believe it or not:

public enum MyEnum {
  INST1() {
    public void foo() {
      //...
    }
  },
  INST2...;
}

What the f…?!

Moshe, my student, is working on some Java parser. You really learn a language when you parse it. Following some question that he had, we found out about the code above. His reaction was less mild then just “what the…” – He nearly freaked out out, and rightfully so.

The rationale behind this piece of code is:

  • Enums in Java are just classes with some syntactic sugar
  • Enum constants are instances of the enum class
  • An instance declaration in Java may include an inner anonymous class declaration
  • → Enum constants may include a class body

Having enumerated constants with their-own class body is apparently a coherent part of the Java language. One can argue, though, how useful or readable this language feature is.

I usually don’t like programming languages impersonation jokes, but replying to this “if programming languages were relationships” post: When I started “dating” Java, it was “the little language that could”. 10 years after, it’s “one big mother” with a whole range of offsprings. With due respect to “all things J”, like JAX-WS, JAXB/StAX, and a whole range of other JSRs – There’s something to say in favour of simplicity too.

(This post was cleared of nasty chauvinistic insinuations toward a female impersonation of Java and other JVM-based programming languages. I hope you appreciate it.)

Posted Tuesday, June 9th, 2009 under Programming.

Tags: ,

4 comments

  1. Actually, I find it very natural.
    To me, enums are a way to implement the Strategy pattern:


    switch (decideAction(args))
    {
    case GoHome: … break;
    case AnotherBeer: … break;
    }
    etc.

    So the Java enums are just a very cool way to do it:

    public enum WhatToDo
    {
    GoHome {@Override void act() { /*walking…*/ }},
    AnotherBeer {@Override void act() { /*drinking…*/ }};

    abstract void act();
    }

    ….
    decideAction(args).act();

    I think this is a major part of what enums are for.

  2. I had serious convulsions while writing that code.

    But it’s over now, and I don’t wish to talk about it anymore. I will bear these scars forever.

  3. Aviv:
    I agree writing this little Strategy piece in separate classes will be a bit more tedious, but just a tiny wee bit. Not enough to discard it in favor of the of the enum – for brevity’s sake.

  4. So true. Honesty and everything reconigezd.

Leave a Reply

Security Code: