Skip to content

Enums for Safety

Goal

In this lab, you'll change all of our hard-coded string options (Small, Regular, Milk, etc.) to be enums for type-safety.

A. Create a Size Enum

  1. Create an enum class named SizeOption that has three choices: SMALL, MEDIUM, and LARGE

    Enum Coding Style

    It's standard Java coding style to have these be all upper-case letters.

    Enum Tutorial

    A small tutorial is here.

  2. Add this toString() implementation to the enum so that it prints more nicely:

    @Override
    public String toString() {
      String name = name().toLowerCase();
      return Character.toUpperCase(name.charAt(0)) + name.substring(1);
    }
    
  3. Change the tests for CoffeeOrder to use the enum instead of the hard-coded String. For example:

    CoffeeOrder order = new CoffeeOrder();
    
    order.size(SizeOption.LARGE);
    
    assertThat(order.price())
        .isEqualTo(200);
    

B. Create Enums for Sweetener and Creamer

Do the same for Creamer and Sweetener:

  1. Replace the String for creamer type with a new enum CreamerOption, that has options for NONE, MILK, HALF_N_HALF.

  2. Add the toString implementation from above.

  3. Change the tests to use this enum.

  4. Make sure the tests continue to pass.

  5. Do the same for Sweetener, using a new enum SweetenerOption, with NONE, SUGAR, and SPLENDA.

  6. Add the toString implementation from above.

  7. Make sure the tests continue to pass.


Once you've completed the above steps, check in with the instructor to review your code.


C. Use Enum Constructor for Better toString

[comment]: <> !!!TODO!!!