开发者

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 b开发者_StackOverflowelow? 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;
        }
      }
      ...
   }  


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜