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());
}
}
在Spring或Hibernate框架中使用可变的getter和setter,在我的自定义代码中使用可变的setter和getter,这是一个好的实践吗。我担心的是:
MyClass myclass = new MyClass();
//assuming that item date was initalized some how.
Date currentDate = myClass.getdate();
currentDate.setMonth( currentDate.getMonth() + 1 );
现在发生的事情是,我刚刚更改了myClass对象中日期变量的值,它可能是系统中bug的主要根源。
我说的对吗?
我也可以在Spring/Hibernate中使用不可变的getter和setter吗?