Inquisitive
Inquisitive

Reputation: 7856

why check validity only after doing a defensive copy?

Please note this 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) > 0)
  throw new IllegalArgumentException(start +" after "+ end);

}

I do not see how it matters if the check for validity of parameters(ie the call to compareTo()) is done before defensively copying the mutable parameters to the constructor ?

Upvotes: 0

Views: 80

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

In a concurrent environment, start.getTime() and end.getTime() could change anywhere in the middle of that constructor.

In particular, if the check were done first, you could have inputs that passed the check, and then another thread modifies them with invalid values, and then the defensive copy copies the invalid values. Result: armageddon.

It's not exactly likely, or that big an issue, but it makes sense to err on the side of caution -- that is, after all, why it's called defensive programming.

Upvotes: 5

Related Questions