Enumeration by integer representation
public class Lecture { public final int dayHeld; /* e.g. to be held on Tuesdays */ public final String title; /* e.g. «PHP introduction» */ public Lecture(final int dayHeld, final String title) { this.dayHeld = dayHeld; this.title = title; } }
Quick and dirty:
Class Driver: final Lecture phpIntro = new Lecture(1 /* Monday */, "PHP introduction"), advancedJava = new Lecture(5 /* Friday */, "Advanced Java");
Error prone:
-
Weeks start on Mondays?
-
Index starts with 0 or 1?
public class Day { static public final int MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7; }
Class Driver: final Lecture phpIntro = new Lecture(Day.MONDAY, "PHP introduction"), advancedJava = new Lecture(Day.FRIDAY, "Advanced Java");
public class Day { ... public static String getDaysName(final int day) { switch (day) { case MONDAY: return "Monday"; case TUESDAY: return "Tuesday"; case WEDNESDAY: return "Wednesday"; case THURSDAY: return "Thursday"; case FRIDAY: return "Friday"; case SATURDAY: return "Saturday"; case SUNDAY: return "Sunday"; default: return "Illegal day's code: " + day; } } }
public class Lecture { public final int dayHeld; ... public String toString() { return "Lecture «" + title + "» being held each " + Day.getDaysName(dayHeld); } }
// Class Driver final Lecture phpIntro = new Lecture( Day.MONDAY, "PHP introduction"), advancedJava = new Lecture( Day.FRIDAY, "Advanced Java"); System.out.println(phpIntro); System.out.println(advancedJava); |
Lecture «PHP introduction» being held each Monday Lecture «Advanced Java» being held each Friday |
// Class Screwed final Lecture phpIntro = new Lecture(88, "PHP introduction"); System.out.println(phpIntro); |
Lecture «PHP introduction» being
held each Illegal day's code: 88 Bad: Not even a compiler warning message! |
/** * Charge double prices on weekends * @param day Day of week * @param amount * @return the effective amount for * given day of week. */ static public int getPrice( final int day, final int amount) { switch (day) { case Day.SATURDAY: case Day.SUNDAY: return 2 * amount; default: return amount; } } |
// Correct System.out.println( getPrice(Day.SUNDAY, 2)); // Argument mismatch System.out.println( getPrice(2, Day.SUNDAY)); 4 7 Bad: Not even a compiler warning message! |