Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use abstraction with classes LocalDate and LocalDateTime?

Tags:

java

dry

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.

like image 415
Karord Avatar asked Oct 24 '25 03:10

Karord


1 Answers

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.

like image 85
Basil Bourque Avatar answered Oct 25 '25 18:10

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!