Heart containing Coding Chica Java 101

What Are My Options? A Simple Java Enum

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Unit Tests
  4. Runtime Code
  5. Maven Build Success
  6. Commit

Introduction

In Java, an enum (AKA an enumeration) may be an option when all of the possible values are things we can list out in a meaningful way and they do not change too frequently.

Some example candidates, are:

  • Days of the week,
  • Months in the year,
  • HTTP status codes
  • Suits for a card deck (hearts, diamonds, clubs, spades)
  • Ranks for a card deck (2-10, J, Q, K, A, Joker)

Additions to enums require code changes, so they are poorly suited for things that change too often:

  • Subscriber / user data,
  • Names or IPs of servers where application is to be deployed. In cloud / Kubernetes mindsets, we think of servers like:
    • cattle – AKA interchangeable, rather than
    • pets – AKA those we are fond of and know their nuances well

Enums allow calling code to:

  • Loop through all possibilities, if desired,
  • Perform input validation – when marshaling the value from a configuration file or a user request,
  • Obtain documentation about the value(s) from the Javadoc,
  • etc.

In this case, let’s add an enum for the units we want to support for an animal’s age.

Unit Tests

Let’s add the unit tests to confirm our expectations. Let’s add a class at src/test/java/codingchica.java101.model/AgeUnitsTest.java.

When we use an enum type, we will get a values() method for free. It will return all of the values we define in the enum. Let’s make sure we configure the values that we would expect to be returned.

package codingchica.java101.model;

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

/**
 * Unit tests for the AgeUnits enum.
 */
class AgeUnitsTest {
    /**
     * Unit tests for the values method, to ensure that the expected enum values have been configured in our code.
     */
    @Nested
    class ValuesTest {
        @Test
        void values_whenInvoked_returnsExpectedValues(){
            // Setup
            AgeUnits[] expectedValues = new AgeUnits[]{AgeUnits.YEARS, AgeUnits.DAYS, AgeUnits.HOURS};

            // Execution
            AgeUnits[] values = AgeUnits.values();

            // Validation
            assertArrayEquals(expectedValues, values, () -> String.format("Expected: %s, Actual: %s", Arrays.toString(expectedValues), Arrays.toString(values)));
        }
    }
}

We want there to be values configured in the enum for:

  • YEARS
  • DAYS
  • HOURS

We are also using the assertArrayEquals(boolean[] expected, boolean[] actual, String message) method in JUnit 5 (Jupiter) – this will compare the size of the arrays, then each of the elements, in order.

Runtime Code

Now, let’s add the enum runtime code. Let’s add a class at: src/main/java/codingchica.java101.model.AgeUnits.java. Instead of a class, we are going to call this one an enum. All we have to do is add the values we want available in this case. This is the simplest form of an enum. It only contains the enumerated value names, but no additional details. It also only contains the methods that Java gives us for free when declaring an enum.

package codingchica.java101.model;


/**
 * The time units we will support for age retrieval.
 */
public enum AgeUnits {
    /**
     * Age should be measured in years.
     */
    YEARS,
    /**
     * Age should be measured in days.
     */
    DAYS,
    /**
     * Age should be measured in hours.
     */
    HOURS;
}

Maven Build Success

Let’s run the Maven build to confirm success.

Commit

We should commit in small batches. Now is a good time.

What Are My Options? A Simple Java Enum

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.