Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defensive copy of Calendar

Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.

eg:

public void setDate(Calendar date) {
    // What to do.... 
}

I am particularly concerned about interleaving of threads when checking for null input and making the copy or am I missing something very apparent?

like image 499
JJ Vester Avatar asked Feb 10 '12 08:02

JJ Vester


1 Answers

(Aimed at a slightly different audience now, I guess...)

I would use clone() if I absolutely had to use Calendar at all (instead of Joda Time). You argue in comments that you're worried about a "naughty subclass" - how would you propose to work around that in any scheme? If you don't know anything about the subclasses involved, and don't trust them, then you've got no way of preserving type-specific data. If you don't trust the subclass not to mess things up, you've got bigger problems in general. How do you trust it to give you the right results when performing date/time calculations?

clone() is the expected way of cloning objects: it's where I'd expect a sensible subclass to hook in any type-specific behaviour it needed. You don't need to know which bits of state are relevant - you just let the type deal with that itself.

Benefits over using Calendar.getInstance() and setting properties yourself:

  • You'll preserve the same calendar type
  • You don't need to worry about forgetting properties: that's the responsibility of the type
  • You're explicitly saying what you want to do, and letting the implementation take care of the how, which is always nice. Your code expresses your intention exactly.

EDIT: In terms of the "thread interleaving" which the original question worries about: the value of the date parameter will not change whatever other threads do. However, if another thread is mutating the contents of the object while you take a defensive copy, that could very easily cause problems. If that's a risk, then you've got bigger issues, basically.

like image 170
Jon Skeet Avatar answered Oct 22 '22 05:10

Jon Skeet