- Use
LocalDate
from java.time, the modern Java date and time API, for a date.
- Catching an exception in the constructor is generally bad. You may do it if you can still initialize the object to a fully valid and meaningful state or you want to wrap the exception into a different exception that you throw to the caller.
java.time
public class FiscalDate {
private LocalDate calendarDate;
}
A LocalDate
is a date in the proleptic Gregorian calendar without time of day. A Calendar
is a date and time of day with time zone, week numbering scheme and more, theoretically in any calendar system. The Calendar
class is also poorly designed and long outdated. So I recommend LocalDate
.
Constructors
Now which constructors do we want? I’d find it natural to have a constructor that accepts a LocalDate
:
public FiscalDate(LocalDate calendarDate) {
this.calendarDate = calendarDate;
}
If you foresee that the caller will sometimes have the date as a string rather than a LocalDate
, providing a convenience constructor that accepts a string is nice:
/** @throws DateTimeParseException if dateString is not a valid date string in format yyyy-MM-dd */
public FiscalDate(String dateString) {
this(LocalDate.parse(dateString));
}
The this()
call calls the constructor from before. It’s similar to a super()
call, only instead of calling a constructor in the superclass it calls a constructor in the same class. LocalDate.parse()
throws a DateTimeParseException
if the string cannot be parsed into a valid date. It’s an unchecked exception, so we need not declare that the constructor may throw it, but it’s nice for the caller to know, so we put it in the Javadoc comment.
I believe that deciding what to do in case of an invalid string date should be the job of the caller, not this class. So throwing the exception is appropriate (as it is or wrapped in a more appropriate exception type). If you were to catch the exception in the constructor, you would need to initialize the object, and I can’t see how you would be able to do that in any meaningful way.
Link