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:

Example

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 :
Defensive copying
Immutable objects
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -