Quata 7: String Addiction

feature image

Quata 7: String Addiction

Here’s another one on strings. The following method classifies the specified day of week into either a weekday or a weekend day (if that’s even a valid expression).

public String determineDayType(String dayOfWeek) {
  if (dayOfWeek == null) {
    return null;
  }

  if ("Saturday".equalsIgnoreCase(dayOfWeek) || "Sunday".equalsIgnoreCase(dayOfWeek)) {
    return "Weekend";
  }

  return "Weekday";
}

Would that work? Of course, it would.

But is that the best way to implement it? In most cases, no. (As with all things, it really depends on how and where this method is used.)

This is likely a case of not using the right tool for the job. Beginning developers tend to have String as their go-to type for anything. It’s like they’re addicted to it (hence, the title of this post). I think it’s usually just because they haven’t explored the rest of the language and are perhaps not even willing to.

If they did, then they would discover these wonderful gems called enums. Both the parameter and the return value have a small, finite set of values. Enums can therefore perfectly represent both of them. Look at this modified version.

NOTE: There is actually a java.time.DayOfWeek defined in the JDK. But let’s ignore it and use our own.

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;
}

Even though it’s longer, here are my reasons why this code is better than the previous one:

  1. Enums more naturally represent both the domain and the range of this particular function.
  2. Instead of returning null for a null value, it explicitly represents and returns a NULL enum value. The caller doesn’t have to worry about handling null return values.
  3. The original method actually had a bug. Since the string input could be anything, the method would return “Weekday” for any bogus non-null value, which is unlikely what you want. In this improved version, you would never even get a bogus non-null value because that’s just how enums work. They have a finite set of values. You cannot force them to have an unrecognized one.

There you go. If you’re addicted to strings yourself, you’re welcome.

I’m actually not satisfied with even this improved version. There’s a particular reason why I chose to ignore the JDK-supplied java.time.DayOfWeek enum. I’ll save my thoughts for the next quata though. Stay tuned.

Leave a Reply

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

Post navigation

  Next Post :
Previous Post :