Consider immutable forms for dates
Some programmers prefer to store date fields not as java.util.Date objects, but in an immutable form such as a long, or an immutable object (such as a DateTime from the date4j library).
Reasons for preferring an immutable representation:
- the mutable Date class requires more care than a long integer
- the Date class itself has many deprecations, replaced by methods in DateFormat, Calendar, and GregorianCalendar
- you may use long as a simple, locale-independent representation of a date, and use the date-related classes to provide a particular view of that date
Here, a simple long is used to encapsulate a date:
package myapp.business; import java.util.*; public final class Movie { public Movie(String aTitle, long aReleaseDate){ fTitle = aTitle; fReleaseDate = aReleaseDate; } public Movie(String aTitle, Date aReleaseDate){ this(aTitle, aReleaseDate.getTime()); } /** * The caller of this method decides on the * presentation format of the date, if necessary. */ public long getReleaseDate(){ return fReleaseDate; } public String getTitle() { return fTitle; } //..other methods elided // PRIVATE private String fTitle; private long fReleaseDate; }
See Also :
Would you use this technique?