Enums considered a codesmell!

You are luckily using enums? You think it’s one of the major improvements to Java in 1.5?

Let’s have a closer look at them. What problem do they address?

  • I can now switch over something I can define. – Great (moan) – But why would you like to switch?
  • Because switching is better than doing if statements. – Why do you have procedural decision logic?
  • It’s clearly readable. – If you are used to procedural style, maybe. But…

… Be honest: Didn’t you ever have to deal with code splattered with identical or similar if statements all over the classes?

In my day-to-day work I see even worse use of enums: The enum construct is misused as a singleton container. Yes, you’ve read correctly: a singleton container. It looks like that:

public enum SingletonContainer {
	Instance;
	
	public void aRealCoolMethod() {
		// here we do the singleton's logic
	}
}

public class UseTheSingleton {

	public void useTheSingleton() {
		// some logic
		SingletonContainer.Instance.aRealCoolMethod();
		// some more logic
	}
}

What a creative way to use enums! – Oh, by the way, did I mention that we are inside a multi-threaded web application?

But that is not the main reason why enums are evil.

Enums are just an easy excuse for not creating the right abstractions. They are handy to use, simple to understand and readily available. But all this does not make them more important than closures, absence of primitives, real generics and many of the other features Java is still missing. The concept is just
a waste of bytes. There is nothing essential that couldn’t be done without them.

We can do it better:

Every enum is a plea for a type. An enum is a type, of course, but…

… Have you ever implemented polymorphic behaviour inside an enum? It starts like that:

package pack;

public enum Showcase {

    First {
        @Override
        public void methodHasToBeimplemented() {
            // do some type specific logic here
        }
    },
    Second {
        @Override
        public void methodHasToBeimplemented() {
            // do some type specific logic here
        }
    };

    public abstract void methodHasToBeimplemented();
}

And now continue following this approach:

You’ll get more and more methods; you’ll get more and more enum constants. Your file will start to cry for relief!

If you look at the compiled classes you’ll find three:

  • Showcase.class
  • Showcase$1.class
  • Showcase$2.class

This means that the compiler knows what you really want: different classes. Why didn’t we do that by our own? – We only lose one thing: We cannot switch over instances of these classes any more. But we got rid of our implicit singletons and can put all the logic into the classes where it belongs. Then we can invoke the methods on the proper objects and have no need for switch statements at all.

7 thoughts on “Enums considered a codesmell!

  1. Hi Andreas,

    imho enums are something really valuable but the Java version of it somehow sucks.

    For some strange reason the Java language designers had that idea to give enums some kind of class semantics instead of simply designing them as enums (as they were designed in Erlang or at least 50 other languages).

    As a consequence of that odd idea of the Java language designers Java enums reveal all those strange behaviours and weird program designs show up.

    So, if you restrict yourself to use enums just as enums – in the common definition, not the Java definition – they are still a quite valuable concept.

    Thus, for me the bottom line is: Enums are not a code smell in themselves. The class-like extensions of Java enums tend to lead to strange smells.

    cu, Uwe

    • Do I really need enums in an object-oriented software design? – Looking forward to talk about that with you, hopefully soon!

  2. I agree with Uwe that Enums are a nice feature. But i actually think the class semantics of Enums are really nice too. The problem is IMHO enums are values by design, i.e. they shouldn’t (correct that: must not) have state.

    If this rule holds Enums are nice and usable. The fact that the compiler creates n .class files if you overwrite methods? Who cares? It becomes a problem if you have lots of lengthy methods. But then you just have to extract some of them into a proper class. Nothing special about Enums here.

    The Enum as a singleton pattern: Again I don’t think the Enum is the culprit here. Singletons are bad in 99% of the cases. But if you have a Singleton. An Enum is probably the implementation with the least amount of code and the smallest chance of bugs and problems.

  3. Using enums as singleton just because it is “safe” and easy to do reminds me of the “good old times” when everybody put constants in interfaces, just because it was convenient..

  4. >> Do I really need enums in an object-oriented software design?

    Hmm, probably not. There are alwasy several ways to solve a problem. Some fit better, some worse. But I think that “fitness factor” does not depend on the solution design in itself but on the problem you have to solve. Sometimes OO is the best design for a problem, sometimes templates might be the best choice, sometimes a functional or imperative design might fit … and sometimes enums are perfectly fine.

    I think the ultimate goal is not to have the “purest” design (whatever that means) but to have a design that is easy to understand – for you and the rest of the world, i.e. whoever might need to change your code later. Code that is easily understood is easy to change, and this means that changes to this code usually bear low risk and effort.

    Therefore, I woldn’t say that doing this or that is “bad” because it does not fit a specific design paradigm perfectly. If the solution is a good and comprehensible solution for the given problem, it is just fine for me.

    This does not mean that enums are a great OO concept and if you really think that OO is the pardigm that fits your problem best it might make sense to think if you really need enums for that but I still don’t think that enums are bad in themselves. Sometimes they fit better, sometimes worse …

    cu, Uwe

  5. Hi, in fact I absolutely *love* Java enums: they’re just perfect for value objects (in the DDD sense) where the set of every possible values is bounded. Believe it or not, but in a recent project I managed to have a majority of value types in this case, deliberatly I must admit. In this case of course I make absolutely sure that each enum constant is totally immutable, and I get the correct equals, hashcode, toString, String or integer serialization, singleton-ness and very efficient collections on them for free, all that with very little code that is very readable.

    The enum polymorphism is also very handy, and sure I never need to instanceof on it, and hardly need to switch on the enum either.

    I’d love that Java enum is completed by a similar construct that would be just like the case class in Scala (when the set of possible values cannot be bounded). And a way to enforce immutability of enums and any other class would be nice too.

  6. Hi, I totally agree… been searching for programmer like you.

    Some guy on my team wants “Enum Oriented Programming” duh?

    Enum as Value Object
    Enum that has business logic
    A Service for the enum (eq, enum holds more than 1 value, try to sort it u’ll be using comparator etc).

    The root of all design principle “Cohesion” and “Coupling”

    then there is such thing as the well known “Single Responsibility Principle”
    (Hope that guy won’t read this cuz he’ll learn lol. )

    So imagine.. He wants an Enum that has a responsibility of (VO, Domain Logic, Etc)

    which is not very cohesive.

    “Enums are evil”? – This guy will probably just tell me “This enum thing was included on” OCJP6..

    Enums are not evil!! Programmers with complicated thinking are evil.. (Believe me I spent a lot of time just reading their horrible codes).

    They should learn how to KISS (Keep it Simple, Stupid!).

    How to use enum?

    I suggest using enum the simple way… as easy as 1 , 2 , 3

    As Constants.. just to coupled certain parameters..

    public class FileConstant {
    public static enum Result {
    SUCCESS, FAILED;
    }
    }
    not as VO.. etc…

    in the end… I still believe in Martin Fowler and Confucius..

    Martin Fowler – Any fool can write code that a computer can understand. Good programmers write code that humans can understand..

    Confucius – Life is really simple, but we insist on making it complicated.

    http://adf.ly/5465896/javaforthewin – Visit My Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s