Why Enum? (Java Why? Article Series 1)

Hi Java people. Ready for analyzing why we need Enum?

I am Huseyin. Have been a .Net developer for years and Java backend and Android developer for 6 years as well as a QA Automation Engineer team member for several projects for 3 years.

Have been observing that some of my friends , especially junior developers, are not completely aware of the point of using a structure a tool. As a developer, by experiencing the reusability, abstraction and the maintainability issues for years, I decided to implement the same structure in my life and abstract myself from answering similar questions 🙂. Thus, put my effort into creating this “Why Java? Article Series”. I just wanna to help developers to code consciously.

The target audience of “Why Java? Article Series” is the ones who already know coding with Java, but also want to understand the underlying language and the system.

Main purpose of these articles is to understand why we need some structures or tools in our framework in order to be conscious while using them. Of course there are a lot of sources about Java on the internet. What I experienced is that some different approaches while explaining the same thing helps people to understand the topics. What I am trying to do is actually that. A different kind of explanation from WHY point.

Articles are prepared to achieve the understanding of the topic from a step by step approach.

If these articles help you to understand a concept, I definitely feel very happy. Feel free to share and comment.

Sharing is learning at the same time! Enjoy.

Using Hard-coded String Literals for Constants

This method is responsible of returning the corresponding list of todo items as a String List, based on the dayName input parameter. Let’s analyze a simple method call below;

Consumer of this method sends an inappropriate input which causes that the method will return an empty list. So, hard-coded String literals are error prone. You may make typos which generally happens.

What about this method call;

This time, there is no typo, but the cases in the switch handles lowercase inputs like “monday”. Generally you will need to use toUpperCase(), toLowerCase(), equalsIgnoreCase() methods to match the case in the switch block. These conversions are sometimes forgotten. Moreover, this kind of conversions makes your code less readable.

As a result; using much double quotes (hard-coded String literals) is not a good practice. Maybe, it’s the worst practice.

How to avoid from error prone hard-coded String literals?

Solution attempt with final variables

Final variables can not be reassigned

By declaring the constants as final, then you guarantee that they will never be changed. Let’s update our method by using these variables in the cases;

It looks better. Let’s call this method;

Looks good. But the method still accepts String parameter. There is no guarantee that any of the developers will not send hard-coded string literal instead of the final constants. So again it is error-prone.

Using final variables for constant values is a reasonable choice in some cases. For example; if you have a constant that is not logically related to any other structure/variable, then using final variables (like above, in a class) is a good choice.

But, if there are some constants which are logically related to each other, then using enum is the best choice. Day names are related to each other logically, pattern is they all belong to Week. So, let’s use them as enum.

Solution attempt with enum

Enum declaration
Method refactored with Enum

Pat attention that the method accepts enum parameter. Method caller can only pass enum (DaysOfWeek).

This code is more solid than the previous two code.

There is no chance to send String variable to this method.

No need to apply toUpperCase(), toLowerCase(), equalsIgnoreCase() methods.

As a result, for related constants, just declare an enum. This approach is less risky than others.

What if I want to use the number (order) of the day?

Enum with 1 instance field

MONDAY enum instance has 1 as value for dayOrder field, and so on.

Let’s analyze our new method which first creates a data map for todos. This method creates a map whose key is the DaysOfWeek enum, value is the list of the todos as String List;

Let’s call this method;

As it is seen from the screenshot, we are calling the getters of each DaysOfWeek enum instances (targetDay, today). For calculating the days difference, we are subtracting today’s order from targetDay’s order.

Here is the output;

Enum with multiple instance fields

Developers encouraged to use SCREAMING_SNAKE_CASE by convention. Because of that, the enum name is not suitable for human-readable strings or non-string values. That’s why sometimes we need to add a more user-friendly value. Look at this example;

This enum implementation has a dayName field for user-friendly print outs. Let’s call this method;

See the print out;

Pay attention to “Wednesday”. Instead of writing WEDNESDAY, Wednesday is more user-friendly and readable.

One Last Thing: Iterating defined enum instances

So What?

Enum is powerful. Because;

  • If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
  • Increases code readability.

Keep in mind these:

  • JavaDoc says: You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time — for example, the choices on a menu, command line flags, and so on.
  • An enum is just like a class, with a fixed set of instances known at compile time.
  • Enums enumerate a fixed set of values, in a self-documenting way.
  • Enums are implicitly final subclasses of java.lang.Enum
  • Enum constants are implicitly public static final
  • “new” keyword can never be used with an enum, even within the enum type itself

Further reading:

Thanks for reading. Hope this helps! See you in the next articles.

PS: Really benefited from especially Baeldung and other Java Tutorial Websites, as well as Official Java Documentation.

Dedicated to Dirty Java Rangers

--

--

Software Developer & SDET/QA

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store