Let's propose that I have the following class
Public MyClass{
Date date;
//Mutable getters and setters
public Date getdate(){
retrurn date;
}
public Date setdate(Date date)
{date = date;}
//Now immutable setter and Getters
public Date getImmutableDate{
return new Date(date.getDate());
}
public void setImmutableDate(Date mydate)
{
date = new Date(mydate.getDate());
}
}
Is it good practice to use mutable getters and setters for Spring or Hibernate Framework and using Immutable setters and getters for my custom coding. What Im i afraid of is the following:
MyClass myclass = new MyClass();
//assuming that item date was initalized some how.
Date currentDate = myClass.getdate();
currentDate.setMonth( currentDate.getMonth() + 1 );
Now what has happened that I just changed the value of date variable inside myClass object and it might be prime root for bugs in system.
Am I correct? Can I use immutable getters and setters for Spring/Hibernate as well?
Note that if you provide a mutable setter and getter, it will eventually be used by people. So that's not a good option.
The question is not particularly related to spring and hibernate, but more to API design. Josh Bloch advises - "minimize mutability". But that means you should use immutable objects, and not create instances each time an object is obtained.
The solution above is to use joda-time's DateTime
object, which is immutable.