Quata 8: Enum Fun

feature image

Quata 8: Enum Fun

Okay, let’s get to it. What do you think about this code, well, besides the fact that the JDK already provides the java.time.DayOfWeek enum? Let’s pretend it doesn’t.

public enum DayType { WEEKDAY, WEEKEND, NULL }

public enum DayOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

public DayType determineDayType(DayOfWeek dayOfWeek) {
  if (dayOfWeek == null} {
    return DayType.NULL;
  }

  if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY)  {
    return DayType.WEEKEND;
  }

  return DayType.WEEKDAY;
}

There’s actually nothing wrong there. However, it could be a sign that the developer had not heard of how Java enums are now much more than constants. They were beefed up in 1.5 to behave like regular classes. They’re no longer your father’s enums. Let’s see how I would change the code to make full use of enums.

public enum DayType { WEEKDAY, WEEKEND, NULL }

public enum DayOfWeek {
  SUNDAY(WEEKEND),
  MONDAY(WEEKDAY) {
    @Override
    public isFunDay() {
      return false;
    }
  },
  TUESDAY(WEEKDAY),
  WEDNESDAY(WEEKDAY),
  THURSDAY(WEEKDAY),
  FRIDAY(WEEKDAY),
  SATURDAY(WEEKEND)

  private final DayType dayType;
 
  DayOfWeek(DayType dayType) {
    this.dayType = dayType;
  }

  public DayType getDayType() {
    return dayType;
  }

  public boolean isWeekday() {
    return getDayType() == DayType.WEEKDAY;
  }

  public boolean isWeekend() {
    return getDayType() == DayType.WEEKEND;
  }

  public boolean isFunDay() {
    return true;
  }
}

As you can see, enums can have their own methods and data members. What I like about the new code above is that the enum encapsulates the day type. A DayOfWeek enum value knows its day type best. It shouldn’t have to require its users to do that work, unlike in the original code where the user had to create the determineDayType() method. In the new code, we didn’t need to write that method anymore. Well, if you still must handle nulls, you could still write a little wrapper method, like so:

public DayType determineDayType(DayOfWeek dayOfWeek) {
  return dayOfWeek != null ? dayOfWeek.getDayType() : DayType.NULL;
}

The isWeekday() and isWeekend() methods are simply convenience methods I thought I’d add while I was at it.

I also added the isFunDay() method to demonstrate polymorphism. And yes, I picked Monday to be the not-fun day because that’s when many of us have to go back to work. Don’t get me wrong. I’m thankful for my job, but I’m sure you know where I’m coming from with this. I’ll let The Bangles do the rest of the talking.

The only thing about enums is that you cannot extend them. All of them inherently extend java.lang.Enum and therefore cannot extend any other class, including fellow enums. I would have extended java.time.DayOfWeek if it was possible.

Leave a Reply

Your email address will not be published. Required fields are marked *

Post navigation

Previous Post :