2

让我们建议我有以下课程

    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 并在我的自定义编码中使用不可变的 setter 和 getter 是否是一种好习惯。我害怕的是以下几点:

MyClass myclass = new MyClass();
//assuming that item date was initalized some how.
Date currentDate = myClass.getdate();
currentDate.setMonth( currentDate.getMonth() + 1 );

现在发生了什么,我刚刚更改了 myClass 对象中日期变量的值,它可能是系统中错误的主要根源。

我对么?我也可以为 Spring/Hibernate 使用不可变的 getter 和 setter 吗?

4

1 回答 1

2

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

这个问题与spring和hibernate并不是特别相关,而是更多地与API设计有关。Josh Bloch 建议 - “最小化可变性”。但这意味着您应该使用不可变对象,而不是每次获得对象时都创建实例。

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

于 2010-11-07T09:46:44.243 回答