Video in progress

Strong Middle 🧱 OOP and SOLID

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. Date was supposed to be a value, but it has setTime(). If you return a Date from a getter, the caller changes the insides of your object: a defensive copy was mandatory.
  • Wrong abstraction. Date is really an Instant in milliseconds, but toString() 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.Date but forbids the time part; toInstant() throws UnsupportedOperationException. Timestamp.equals(Date) is not symmetric, which the javadoc itself admits.
  • Thread safety. Calendar and SimpleDateFormat are 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 Clock you 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.