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¶
-
Create an
enumclass namedSizeOptionthat has three choices:SMALL,MEDIUM, andLARGEEnum Coding Style
It's standard Java coding style to have these be all upper-case letters.
Enum Tutorial
A small tutorial is here.
-
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); } -
Change the tests for
CoffeeOrderto use theenuminstead 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:
-
Replace the
Stringfor creamer type with a new enumCreamerOption, that has options forNONE,MILK,HALF_N_HALF. -
Add the
toStringimplementation from above. -
Change the tests to use this enum.
-
Make sure the tests continue to pass.
-
Do the same for
Sweetener, using a new enumSweetenerOption, withNONE,SUGAR, andSPLENDA. -
Add the
toStringimplementation from above. -
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!!!
Once you've completed the above steps, check in with the instructor to review your code.