Search code examples
javajavabeanseffective-java

Example of an elegant implementation of 'Defensive Copying' of a nullable java.util.Date in a JavaBean's getter/setter implementation?


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;
        }
      }
      ...
   }  

Solution

  • 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 :)