Enumeration by dedicated class

Figure 355. 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 356. 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 357. switch no longer works Slide presentation

Reverting to if .. else if ...

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 358. Re-writing getPrice() Slide presentation
/**
 * Charge double prices on weekends
 * @param day Day of week
 * @param amount
 * @return the effective amount depending on day of week.
 */
static public int getPrice(final Day day, final int amount) {
  if (Day.SATURDAY == day || Day.SUNDAY == day) {
    return 2 * amount;
  } else {
    return amount;
  }
}

Figure 359. Compile time argument mismatch error Slide presentation

Preventing method argument order mismatch:

// Class Driver

// o.K.
System.out.println(Screwed2.getPrice(Day.SUNDAY,  2));

// Argument mismatch causing compile time type violation error
System.out.println(Screwed2.getPrice(2, Day.SUNDAY));

Figure 360. 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