Video in progress
Why are `java.util.Date` and `Calendar` called a bad OOP design example, and which mistakes did `java.time` fix?
Date is mutable, misnamed (it's a point in time, not a date), its months count from 0 and its years from 1900, and java.sql.Date inherits from it and breaks LSP. java.time brought immutable value types, clear concepts (LocalDate, Instant, ZonedDateTime) and a safe API.
📖 Answer
The problems of the old API are each a lesson in OOP:
- Mutable value.
Datewas supposed to be a value, but it hassetTime(). If you return aDatefrom a getter, the caller changes the insides of your object: a defensive copy was mandatory. - Wrong abstraction.
Dateis really anInstantin milliseconds, buttoString()shows it in the local time zone and everybody thinks of it as a "date". - Confusing API.
new Date(2024, 1, 15)is actually February 15 of the year 3924: the year counts from 1900 and the month from 0. - Inheritance mistake.
java.sql.Date extends java.util.Datebut forbids the time part;toInstant()throwsUnsupportedOperationException.Timestamp.equals(Date)is not symmetric, which the javadoc itself admits. - Thread safety.
CalendarandSimpleDateFormatare mutable.
The java.time approach (Java 8, JSR-310):
LocalDate due = LocalDate.of(2024, Month.FEBRUARY, 15); // explicit, 1-based
LocalDate next = due.plusMonths(1); // a new object, due did not change
Instant now = Instant.now(clock); // a point in time
ZonedDateTime tashkent = now.atZone(ZoneId.of("Asia/Tashkent"));
- each concept is a separate type, and they don't mix;
- everything is immutable and thread-safe;
- composition and interfaces (
Temporal,TemporalAdjuster) instead of inheritance; - through
Clockyou can swap the time in tests.
The practical rule: don't use Date/Calendar in new code. JPA (Hibernate 6) and Jackson (jackson-datatype-jsr310) work fully with java.time.
Sign up to mark studied questions and save your progress.