I know what IllegalStateException is for, but I wonder if in some cases I should actually use it or it's just a matter of design.
Let's say I have a Tournament
class that models a sports tournament and a tournament has a Schedule
, which needs to be calculated. So unless you actually launch the resolution process that generates the schedule, you don't have a schedule, and trying to get it before this state actually happens should be treated somehow. I thought this would be an appropriate scenario where an IllegalStateException
should be thrown: if the schedule hasn't been calculated yet, throw it. Let's see:
public Tournament {
private Schedule schedule;
public boolean solve() {
boolean solved = solver.solve();
if (solved)
schedule = solver.getSolution();
return solved;
}
public Schedule getSchedule() {
if (schedule == null)
throw new IllegalStateException("Schedule has not been calculated yet");
return schedule;
}
// This udpates the current schedule with the "next" solution.
// Same logic regarding the ISE is applied
public boolean nextSchedule() {
if (schedule == null)
throw new IllegalStateException("Schedule has not been calculated yet");
boolean hasNextSolution = solver.update();
if (hasNextSolution)
schedule = solver.getSolution();
return hasNextSolution;
}
}
Is ISE
being used appropriately here? Should changes be made in the class design instead?
What are the best practices?