Spring setter / getters和Mutable Variables

时间:2010-11-07 09:43:10

标签: java hibernate spring spring-mvc mutable

我们建议我有以下课程

    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 Framework的可变getter和setter以及使用Immutable 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吗?

1 个答案:

答案 0 :(得分:2)

请注意,如果您提供可变的setter和getter,它最终将被人们使用。所以这不是一个好的选择。

这个问题与spring和hibernate没有特别的关系,但更多的是API设计。 Josh Bloch建议 - “尽量减少可变性”。但这意味着您应该使用不可变对象,而不是每次获取对象时都创建实例。

上面的解决方案是使用joda-timeDateTime对象,这是不可变的。