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);
}
}
|
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 |
|
// Correct System.out.println( getPrice(Day.SUNDAY, 2)); // Argument mismatch System.out.println( getPrice(2, Day.SUNDAY)); 4 7 Bad: No warning message whatsoever! |