This is more of a follow-up to questions 1 & 2.
As told in the questions the below code
public Date getSomeDate() {
return someDate;
}
will give you the findbug error issue.
The suggested solution was to duplicate the Date object in both getters and setters like
public Date getSomeDate() {
return new Date(someDate.getTime());
}
Is this a good approach or are there any alternative ways to this?
Is there any Immutable Date library available in java that can overcome this issue?
Attention Folks...
besides adapting both the getter and the setter you need to take care about null values:
public Date getSomeDate() {
if (this.someDate == null) {
return null;
}
return new Date(this.someDate.getTime());
}
public void setSomeDate(final Date someDate) {
if (someDate == null) {
this.someDate = null;
} else{
this.someDate = new Date(someDate.getTime());
}
}
JodaTime has immutable dates.
Sure, it's okay to use a Date
constructor in a getter, why wouldn't it be?
That said, just because FindBugs pegs mutable state as a potential error, it doesn't mean it's intrinsically worth caring about–it depends on how the class is being used. Immutability eliminates one type of bug, which you may or may not need to care a lot about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With