I have the following code:
LocalDate date;
LocalDate minDate;
//constructor...
if(date.isBefore(minDate)){
throw new RuntimeException();
}
and similar with LocalDateTime:
LocalDateTime date;
LocalDateTime minDate;
//constructor...
if(date.isBefore(minDate)){
throw new RuntimeException();
}
Can I use some interface or abstract class thanks to which I wouldn't have to write the same code twice? I can't find such an interface. As you can see I am using only 'isBefore' and 'isAfter' methods.
There are more general types shared by these classes, such as Temporal. But they are not meant to be used by app developers generally.
And those more general types do not share the isBefore/isAfter methods.
I think you are being fooled by the coincidentally named methods into thinking that these date-time classes are mere variations of each other. But they are not. A LocalDate is really a different animal than LocalDateTime. And so, in reference to your DRY tag, you actually are not repeating yourself here. Trying to abstract away the distinction between a date-only and a date-with-time is not valid.
In contrast, notice how LocalDate implements the more general interface ChronoLocalDate, where the isBefore/isAfter methods come from. That interface is shared among five classes within Java (HijrahDate, JapaneseDate, LocalDate, MinguoDate, ThaiBuddhistDate) and even more classes in the ThreeTen-Extra project. Those classes are the same kind of animal, various ways to identify each date on a calendar. For these classes abstracting all these classes as a ChronoLocalDate is logically appropriate, and (apparently) useful to the java.time framework.
Note that I am not suggesting the use of ChronoLocalDate in your app. The Javadoc clearly warns us against such usage as a general rule. I’m merely trying to show that date-only classes are “kind of the same” while date-only and date-with-time classes are not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With