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
enum
class namedSizeOption
that has three choices:SMALL
,MEDIUM
, andLARGE
Enum 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
CoffeeOrder
to use theenum
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:
-
Replace the
String
for creamer type with a new enumCreamerOption
, that has options forNONE
,MILK
,HALF_N_HALF
. -
Add the
toString
implementation 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
toString
implementation 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!!!