Java Enums: You have grace, elegance and power and this is what I Love!

While Java 8 is coming, are you sure you know well the enums that were introduced in Java 5? Java enums are still underestimated, and it’s a pity since they are more useful than you might think, they’re not just for your usual enumerated constants!

Java enum is polymorphic

Java enums are real classes that can have behavior and even data.

Let’s represent the Rock-Paper-Scissors game using an enum with a single method. Here are the unit tests to define the behavior:

public void paper_beats_rock() {
public void scissors_beats_paper() {
public void rock_beats_scissors() {
And here is the implementation of the enum, that primarily relies on the ordinal integer of each enum constant, such as the item N+1 wins over the item N. This equivalence between the enum constants and the integers is quite handy in many cases.
/** Enums have behavior! */
public enum Gesture {
	ROCK() {
		// Enums are polymorphic, that's really handy!
		public boolean beats(Gesture other) {
			return other == SCISSORS;

	// we can implement with the integer representation
	public boolean beats(Gesture other) {
		return ordinal() - other.ordinal() == 1;

Notice that there is not a single IF statement anywhere, all the business logic is handled by the integer logic and by the polymorphism, where we override the method for the ROCK case. If the ordering between the items was not cyclic we could implement it just using the natural ordering of the enum, here the polymorphism helps deal with the cycle.

You can do it without any IF statement! Yes you can!

This Java enum is also a perfect example that you can have your cake (offer a nice object-oriented API with intent-revealing names), and eat it too (implement with simple and efficient integer logic like in the good ol’ days).

Over my last projects I’ve used a lot enums as a substitute for classes: they are guaranted to be singleton, have ordering, hashcode, equals and serialization to and from text all built-in, without any clutter in the source code.

If you’re looking for Value Objects and if you can represent a part of your domain with a limited set of instances, then the enum is what you need! It’s a bit like the Sealed Case Class in Scala, except it’s totally restricted to a set of instances all defined at compile time. The bounded set of instances at compile-time is a real limitation, but now with continuous delivery, you can probably wait for the next release if you really need one extra case.

Well-suited for the Strategy pattern

Let’s move to to a system for the (in-)famous Eurovision song contest; we want to be able to configure the behavior on when to notify (or not) users of any new Eurovision event. It’s important. Let’s do that with an enum:

/** The policy on how to notify the user of any Eurovision song contest event */
public enum EurovisionNotification {

	/** I love Eurovision, don't want to miss it, never! */
		public boolean mustNotify(String eventCity, String userCity) {
			return true;

	 * I only want to know about Eurovision if it takes place in my city, so
	 * that I can take holidays elsewhere at the same time
		// a case of flyweight pattern since we pass all the extrinsi data as
		// arguments instead of storing them as member data
		public boolean mustNotify(String eventCity, String userCity) {
			return eventCity.equalsIgnoreCase(userCity);

	/** I don't care, I don't want to know */
	NEVER() {
		public boolean mustNotify(String eventCity, String userCity) {
			return false;

	// no default behavior
	public abstract boolean mustNotify(String eventCity, String userCity);


And a unit test for the non trivial case ONLY_IF_IN_MY_CITY:

public void notify_users_in_Baku_only() {
	assertThat(ONLY_IF_IN_MY_CITY.mustNotify("Baku", "BAKU")).isTrue();
	assertThat(ONLY_IF_IN_MY_CITY.mustNotify("Baku", Paris")).isFalse();

Here we define the method abstract, only to implement it for each case. An alternative would be to implement a default behavior and only override it for each case when it makes sense, just like in the Rock-Paper-Scissors game.

Again we don’t need the switch on enum to choose the behavior, we rely on polymorphism instead. You probably don’t need the switch on enum much, except for dependency reasons. For example when the enum is part of a message sent to the outside world as in Data Transfer Objects (DTO), you do not want any dependency to your internal code in the enum or its signature.

For the Eurovision strategy, using TDD we could start with a simple boolean for the cases ALWAYS and NEVER. It would then be promoted into the enum as soon as we introduce the third strategy ONLY_IF_IN_MY_CITY. Promoting primitives is also in the spirit of the 7th rule “Wrap all primitives” from the Object Calisthenics, and an enum is the perfect way to wrap a boolean or an integer with a bounded set of possible values.

Because the strategy pattern is often controlled by configuration, the built-in serialization to and from String is also very convenient to store your settings.

Perfect match for the State pattern

Just like the Strategy pattern, the Java enum is very well-suited for finite state machines, where by definition the set of possible states is finite.

A baby as a finite state machine (picture from

Let’s take the example of a baby simplified as a state machine, and make it an enum:

 * The primary baby states (simplified)
public enum BabyState {


	private final BabyState next;

	private BabyState(BabyState next) { = next;

	public BabyState next(boolean discomfort) {
		if (discomfort) {
			return CRY;
		return next == null ? EAT : next;

And of course some unit tests to drive the behavior:

public void eat_then_sleep_then_poop_and_repeat() {

public void if_discomfort_then_cry_then_eat() {

Yes we can reference enum constants between them, with the restriction that only constants defined before can be referenced. Here we have a cycle between the states EAT -> SLEEP -> POOP -> EAT etc. so we need to open the cycle and close it with a workaround at runtime.

We indeed have a graph with the CRY state that can be accessed from any state.

I’ve already used enums to represent simple trees by categories simply by referencing in each node its elements, all with enum constants.

Enum-optimized collections

Enums also have the benefits of coming with their dedicated implementations for Map and Set: EnumMap and EnumSet.

These collections have the same interface and behave just like your regular collections, but internally they exploit the integer nature of the enums, as an optimization. In short you have old C-style data structures and idioms (bit masking and the like) hidden behind an elegant interface. This also demonstrate how you don’t have to compromise your API’s for the sake of efficiency!

To illustrate the use of these dedicated collections, let’s represent the 7 cards in Jurgen Appelo’s Delegation Poker:

public enum AuthorityLevel {

	/** make decision as the manager */

	/** convince people about decision */

	/** get input from team before decision */

	/** make decision together with team */

	/** influence decision made by the team */

	/** ask feedback after decision by team */

	/** no influence, let team work it out */

There are 7 cards, the first 3 are more control-oriented, the middle card is balanced, and the 3 last cards are more delegation-oriented (I made that interpretation up, please refer to his book for explanations). In the Delegation Poker, every player selects a card for a given situation, and earns as many points as the card value (from 1 to 7), except the players in the “highest minority”.

It’s trivial to compute the number of points using the ordinal value + 1. It is also straightforward to select the control oriented cards by their ordinal value, or we can use a Set built from a range like we do below to select the delegation-oriented cards:

	public int numberOfPoints() {
		return ordinal() + 1;

	// It's ok to use the internal ordinal integer for the implementation
	public boolean isControlOriented() {
		return ordinal() < AGREE.ordinal();

	// EnumSet is a Set implementation that benefits from the integer-like
	// nature of the enums
	public static Set DELEGATION_LEVELS = EnumSet.range(ADVISE, DELEGATE);

	// enums are comparable hence the usual benefits
	public static AuthorityLevel highest(List levels) {
		return Collections.max(levels);

EnumSet offers convenient static factory methods like range(from, to), to create a set that includes every enum constant starting between ADVISE and DELEGATE in our example, in the declaration order.

To compute the highest minority we start with the highest card, which is nothing but finding the max, something trivial since the enum is always comparable.

Whenever we need to use this enum as a key in a Map, we should use the EnumMap, as illustrated in the test below:

// Using an EnumMap to represent the votes by authority level
public void votes_with_a_clear_majority() {
	final Map<AuthorityLevel, Integer> votes = new EnumMap(AuthorityLevel.class);
	votes.put(SELL, 1);
	votes.put(ADVISE, 3);
	votes.put(INQUIRE, 2);

Java enums are good, eat them!

I love Java enums: they’re just perfect for Value Objects in the Domain-Driven Design sense where the set of every possible values is bounded. In a recent project I deliberatly managed to have a majority of value types expressed as enums. You get a lot of awesomeness for free, and especially with almost no technical noise. This helps improve my signal-to-noise ratio between the words from the domain and the technical jargon.

Or course I make sure each enum constant is also 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.

(picture from – Jim Barnabee article)”]
The power of polymorphism

The enum polymorphism is very handy, and I never use instanceof on enums and I hardly need to switch on the enum either.

I’d love that the Java enum is completed by a similar construct just like the case class in Scala, for when the set of possible values cannot be bounded. And a way to enforce immutability of any class would be nice too. Am I asking too much?

Also <troll>don’t even try to compare the Java enum with the C# enum…</troll>

Read More

The String Obsession anti-pattern

This anti-pattern is about Using String instances all the time instead of more powerful objects. This is a special case of primitive obsession.


Here are some flavours of this anti-pattern:

  • String as keys in a Map: I have seen calls to toString() on objects just to use their String representation as a key in a Map: map.put(myPerson.toString(), “someValue”).
  • String as enum (“In Progress” , “Done”, “Error”), with tests using equal() to trigger the corresponding logic.
  • Array or Collection of String to mimic a data structure, in which case the ordering matters: {“firstname”, “lastname”}.
  • String with a special format that makes it parsable: “value1_value2”, but used all over the place as is, with parsing code all over the place.
  • String in XML format used everywhere as is, rather than a corresponding tree of objects (a DOM); again there is a lot of parsing everywhere.

The problem

string_obsessionWhy not use “real” Java objects instead of Strings? Value Objects would be much easier to use, and would be more efficient in many cases, whereas String obsession comes with serious troubles:

  • Repeated parsing is CPU-intensive and allocates a lot of new objects each time
  • The code to parse and interpret a String must be spread all over the code base, leading to clutter and plenty of quasi-duplication
  • When used to represent meaningful domain concepts, Strings have no method dedicated to the business. The domain operations must be managed elsewhere and selected with conditionals; on the contrary, using value objects makes your life easier everytime you use them.
  • String values also need to be parsed to be validated. String values do not catch potential issues early, they will only be discovered when really used; on the other hand, value objects can be validated and can catch issues as soon as they are constructed


Use Value Objects, that are immutable, with efficient and safe equals() and hashcode(), the convenient toString() and every useful member method that can make them easy to use and. On inputs, convert the incoming format (e.g. String) into the corresponding full-featured object as soon as possible, and use the object as much as possible. In practice the objects can be used everywhere, everytime, as long as they remain within the same VM.

Why the String obsession?

Sure, there are some reasons why some people favour Strings rather than creating additional objects:

  • String are already available in i/o, hence you may consider it is memory efficient to just keep them
  • String are immutable, behave well as keys, and are easy to inspect in debug
  • You may assume that i/o represent the majority of cases in the application
  • You may consider that creating additional value objects mean more code therefore more effort and more maintenance

I strongly believe all these reasons are short-sighted, if not wrong. The burden of having to interpret the business meaning of a String each time is definitely a loss compared to creating a object with a meaning as soon as possible in i/o and use the object and its methods thereafter. Even for persistence and on-screen display, having an object with methods and accessors make our life easier than just using Strings!

Read More

Design your value objects carefully and your life will get better!

Many concepts look obvious because they are used often, not because they are really simple.

Small quantities that we encounter all the time in most projects, such as date, time, price, quantity of items, a min and a max… hardly are a subject of interest from developers “as it is obvious that we can represent them with primitives”.

Yes you can, but you should not.

I have experienced through different projects that every decision to use a new value value object or to improve an existing value object, even very small and trivial, was probably the design decision that yields the most benefit in every further development, maintenance or evolution. This comes from the simple fact that using something simpler “all the time” just makes our life simpler all the time.

We often dont pay attention to the usual chair, however it was carefully designed.
We often dont pay attention to the usual chair, however it was carefully designed.

As a reminder, value objects are objects with an identity solely defined by their data. Using value objects brings many typical benefits of Object Orientation, such as:

  1. One value object often gathers several primitives together, and one thing is always simpler that a few things
  2. The value object can be fully unit-tested: this gives a tremendous return, because once it is trusted there will simply be no bug about it any more
  3. Methods that encapsulate even the simplest expression with a good name tells exactly what it does, instead of having to interpret the expression every time (think of isEmpty() instead of “size() == 0”, it does save some time each time)
  4. The value object is a place to put documentation such as the corresponding unit and other conventions, and have them enforced. Static creators makes creation easy, self-explanatory, can enforce the validations and help select the right unit (percent, meter, currency)
  5. The method toString() can just tell in a pretty-formatted fashion what it is, and this is precious!
  6. The value object can also define various abilities, such as being Comparable, being immutable, be reused in a Flyweight fashion etc.

And of course, when needed it can be changed to evolve, without breaking the code using it. I could not imagine a team claiming to be really agile without the ability at least to evolve its most basic concepts in an easy way.

The first time it takes some extra time to build a value object, as opposed to jumping to a few primitives; but being lazy actually means doing less in the long run, not just right now.

Read More