Defensive copying
Immutable objects
java.util.Date
objects, but in an immutable form.
For example, you could use:
LocalDateTime
, or LocalDate
(JDK 8+)
String
Long
representing the number of milliseconds since some initial epoch
DateTime
class in the date4j library also addresses the issue, but when
JDK 8+ is available, it likely shouldn't be used.)
Reasons for preferring an immutable representation:
java.util.Date
class requires more carejava.util.Date
class itself has many deprecations, replaced by methods
in DateFormat
,
Calendar
,
and GregorianCalendar
Here, a LocalDate
is used to encapsulate a date:
import java.time.LocalDate; import java.util.Objects; public class Film { public static void main(String... args) { Film film = new Film("The Lobster", LocalDate.parse("2015-10-16")); log(film.getReleasedOn()); } public Film(String name, LocalDate releasedOn){ this.name = name; this.releasedOn = releasedOn; } public String getName() { return name; } public LocalDate getReleasedOn() { return releasedOn; } //...elided // PRIVATE private String name; /** Immutable. Has no time-zone information. The time-zone is simply treated as implicit, according to the context. */ private LocalDate releasedOn; private static void log(Object thing){ System.out.println(Objects.toString(thing)); } }