From date should be lower than to date
TL;DR: Intervals are there. Why use plain dates?
Problems
Missing abstraction
Not enforced invariants
Primitive Obsession
Bijection Fault
Fail Fast principle violation
Solutions
- Create and use an Interval Object
Context
The restriction "From date should be lower than to date" means that the starting date of a certain interval should occur before the ending date of the same interval.
The "From date" should be a date that comes earlier in time than the "To date".
This restriction is in place to ensure that the interval being defined makes logical sense and that the dates used to define it are in the correct order.
We all know it. But we miss creating the Interval object.
Would you create a Date as a pair of 3 Integer numbers? Certainly, not.
This is the same.
Sample Code
Wrong
val from = LocalDate.of(2018, 12, 9)
val to = LocalDate.of(2022, 12, 22)
val elapsed = elapsedDays(from, to)
fun elapsedDays(fromDate: LocalDate, toDate: LocalDate): Long {
return ChronoUnit.DAYS.between(fromDate, toDate)
}