Enumeration by dedicated class

Figure 363. Enumeration by class instances Slide presentation

Roadmap:

  • Define a dedicated enumeration representing class.

  • Create exactly one class instance per enumeration value.

  • Enumeration value equality comparison by virtue of the == operator.


Figure 364. Class instance per enumeration value Slide presentation
public class Day {

  static public final Day
    MONDAY    = new Day(),
    TUESDAY   = new Day(),
    WEDNESDAY = new Day(),
    THURSDAY  = new Day(),
    FRIDAY    = new Day(),
    SATURDAY  = new Day(),
    SUNDAY    = new Day();
}

Note: Class without instance attributes.


Figure 365. switch no longer works Slide presentation

Reverting to if .. else if ... required 🙄

public static String getDaysName(final Day day) {
  if (MONDAY == day) {  // Switch no longer possible, sigh!
    return "Monday";
  } else if (TUESDAY == day) {
      ...
  } else if (SUNDAY == day) {
    return "Sunday";
  } else {
    return "Illegal day instance: " + day;
  }
}

Figure 366. Re-writing getPrice() Slide presentation
/**
* Charge double prices on weekends
* @param day Day of week
* @param amount Product costs
* @return the effective amount for given day of week.
*/
static public int getPrice(final int day, final int amount) {
  if (Day.SATURDAY == day || Day.SUNDAY == day) {
    return 2 * amount;
  } else {
    return amount; }}
System.out.println(Screwed2.getPrice(Day.SUNDAY,  2));   // Class Driver, o.K.
System.out.println(Screwed2.getPrice(2, Day.SUNDAY));  // Argument mismatch, compile time error

Figure 367. Pitfall: Creating an undesired instance Slide presentation
Class Screwed:

final Day PAST_SUNDAY = new Day();

final Lecture phpIntro = new Lecture(
     PAST_SUNDAY, "PHP introduction");

System.out.println(phpIntro.toString());
Lecture «PHP introduction» being
held each Illegal day instance: 
de.hdm_stuttgart.mi.sd1.
class_wrapper.Day@63961c42