Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Findbugs issues with mutability of Date object in Java

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?

like image 620
ManuPK Avatar asked Oct 28 '11 17:10

ManuPK


2 Answers

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());
  }
}
like image 84
Martin Bluemel Avatar answered Nov 05 '22 21:11

Martin Bluemel


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.

like image 23
Dave Newton Avatar answered Nov 05 '22 22:11

Dave Newton