I know I can improvise this little bit (eliminate explicit throw) by using Preconditions class from Guava or by extracting method isValidDayOfWeek(). But that is not what I am looking for. Is there a way to simplify this logic without using the switch statement? This check is making sure that startDayOfWeek is one of the 7 values of the week.
public static TimeSlice getPreviousWeek(Date referenceDate, int startDayOfWeek)
{
if (!((startDayOfWeek == Calendar.SUNDAY) || (startDayOfWeek == Calendar.MONDAY) || (startDayOfWeek == Calendar.TUESDAY)
|| (startDayOfWeek == Calendar.WEDNESDAY) || (startDayOfWeek == Calendar.THURSDAY)
|| (startDayOfWeek == Calendar.FRIDAY) || (startDayOfWeek == Calendar.SATURDAY)))
{
throw new IllegalArgumentException("getPreviousWeek(): invalid startDayOfWeek:" + startDayOfWeek);
}
}
The values of those days of the week are guaranteed and documented, with SUNDAY==1 and SATURDAY==7 so you just want:
If you wanted to make it crystal clear, you could always use:
(That’s using Guava‘s
ImmutableSet, but you could use something else if you want.)