title: How do you make a defensive copy in a constructor if the input parameter is invalid
body: <p>In Josh Bloch's excellent book <a href="http://java.sun.com/docs/books/effective/" rel="nofollow">Effective Java</a> under Item 39 he says:</p>
  
  <blockquote>
    <p>"[D]efensive copies are made <i>before</i> checking the validity of the parameters, and the validity check is performed on the copies rather than on the originals."</p>
  </blockquote>
  
  <p>The example given is as follows:</p>
  
  <pre><code>public Period(Date start, Date end) {
     this.start = new Date(start.getTime());
     this.end = new Date(end.getTime());
  
     if(this.start.compareTo(this.end) &gt; 0)
        throw new IllegalArgumentException("...");
     }
  }
  </code></pre>
  
  <p>The problem with doing the validity checks after the defensive copy is that an invalid parameter can cause the creation of the copy to fail. For example, the class above will throw a <code>NullPointerException</code> if you pass it a <code>null</code> for <code>start</code> or <code>end</code>. </p>
  
  <p>If I move the validity check before the defensive copy, I am vulnerable to the time-of-check/time-of-use attack that Bloch cites as the reason for doing the defensive copy first.</p>
  
  <p>My question is what is a way around this? I can't believe I'm the first person to see this problem in a well read book (though the errata for the book says nothing about it), so maybe I'm just missing something.</p>