2

Is there an elegant Java implementation of Joshua Bloch's defensive copying techniques using the example below? The nullChecking is really the issue I think, but perhaps there is a much simpler way to achieve defensive copying.

   public class Audit {
      private Date dateCompleted;
      ...      
      public Audit() {
        super();
      }

      //defensive copy of dateCompleted
      public final Date getDateCompleted() {
        if (dateCompleted != null){
          return new Date(dateCompleted.getTime());
        }else{
          return null;
        }
      }

      public final void setDateCompleted(Date dateCompleted) {
        if (dateCompleted != null){
          this.dateCompleted = new Date(dateCompleted.getTime());
        }else{
          this.dateCompleted = null;
        }
      }
      ...
   }  
Brian
  • 13,412
  • 10
  • 56
  • 82

1 Answers1

5

Well you can have a convenience method in a utility class:

public class DateUtils {
    public static Date defensiveCopy(Date date) {
        return date == null ? null : new Date(date.getTime());
    }
}

Then:

public final void setDateCompleted(Date dateCompleted) {
    this.dateCompleted = DateUtils.defensiveCopy(dateCompleted);
}

Static imports can hide the DateUtils part if you want.

Alternatively, you can use Joda Time which mostly uses immutable types and is a much better API in general :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was looking in apache commons DateUtils for this method - which led to me posting the question. – Brian Sep 26 '11 at 18:44
  • @Brian: You might want to change to another name for your own utility class then :) I would really recommend the Joda Time option if you *possibly* can though... – Jon Skeet Sep 26 '11 at 19:04