In Josh Bloch's excellent book Effective Java in paragraph 39 he says:
"[D] extensive copies have been made before , checking that the parameters are correct, and validation is done on the copies, not the originals."
The above example is as follows:
public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end = new Date(end.getTime()); if(this.start.compareTo(this.end) > 0) throw new IllegalArgumentException("..."); } }
The problem with performing validation checks after a protective copy is that an invalid parameter can cause the copy to fail. For example, the class above will throw a NullPointerException if you pass it null for start or end .
If I translate the validation before the protective copy, I am vulnerable to a time / time attack of use, which Bloch cites as the reason for the first protective copy.
My question is, what is this way? I canโt believe that I am the first person to see this problem in a well-read book (although there is nothing about this in this book), maybe I just missed something.
stand source share