Reputation: 151
I have the following problem. I need to validate date and time, so it returns false if the day of the week is Tuesday orThursday and the time is between 2:00 and 3:00 PM.
I have two options:
if (appointmentRequest.getDateTime().getDayOfWeek() == DayOfWeek.TUESDAY
|| appointmentRequest.getDateTime().getDayOfWeek() == DayOfWeek.THURSDAY) {
if (appointmentRequest.getDateTime().getHour() == 2) {
return false;
}
}
Option 2:
if ((appointmentRequest.getDateTime().getDayOfWeek() == DayOfWeek.TUESDAY
|| appointmentRequest.getDateTime().getDayOfWeek() == DayOfWeek.THURSDAY)
&& (appointmentRequest.getDateTime().getHour() == 2)) {
return false;
}
What is the best practice in cases like this?
Upvotes: 1
Views: 169
Reputation: 200138
I find your question a bit of a false dichotomy; clarity can be won in other ways, for example by a combination of extracting the common subexpression into a variable and relying on EnumSet
:
LocalDateTime dt = appointmentRequest.getDateTime();
if (EnumSet.of(TUESDAY, THURSDAY).contains(dt.getDayOfWeek()) && dt.getHour() == 2) {
return false;
}
Upvotes: 2
Reputation: 234635
Logically they are equivalent, and computationally there will be negligible difference in the run times.
Always strive for clarity and the one that is going to be more extensible, and simpler to maintain. As a rule of thumb, bear in mind that although you typically write a line of code once, you'll debug it hundreds of times.
My instinct is that the first option fits that. It's easy to set a line break on the second if
if you make that choice.
Upvotes: 5