How to make a protective copy in the constructor if the input parameter is invalid

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.

+4
source share
4 answers

Like others, you check for null before copying parameters.

If I translate the validation before the security copy, I am vulnerable to the validation time / usage time that Bloch cites as the reason for the first security copy.

No, the hacker will not be able to change the link to the actual instance to the null link or vice versa. Copying is done to avoid changes in the state of internal arguments from another thread.

+1
source

A defensive copy is a good strategy, but it has its own premises ... One has something that you can really copy ...

IMHO this means that a null check must be performed BEFORE THE COPPER And if it does not work, it throws an appropriate exception ...

+1
source

You do not need to be โ€œprotectiveโ€ with respect to validating the pointer. A pointer cannot change to zero or another object, but only the contents of what it points to can change.

When creating "protective copies" you need to use the "pen" to check the terrain before you step on it - check each pointer for accuracy, before using it, limit the borders of borders, etc. Itโ€™s not difficult, just tiresome, and it takes a little bit of intelligence.

[Nor is there much harm, just letting NullPointerExceptions bubble up.]

+1
source

I do not understand the problem. The exception structure already takes into account invalid arguments.

0
source

All Articles