Spring setter/getter 和可变变量
让我们建议我有以下类,
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 对象内的日期变量的值,它可能是系统中错误的主要根源。
我说得对吗? 我也可以在 Spring/Hibernate 中使用不可变的 getter 和 setter 吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,如果您提供可变的 setter 和 getter,它最终会被人们使用。所以这不是一个好的选择。
这个问题与spring和hibernate并不是特别相关,而更多的是与API设计相关。乔什·布洛赫(Josh Bloch)建议——“尽量减少可变性”。但这意味着您应该使用不可变对象,而不是每次获取对象时都创建实例。
上面的解决方案是使用 joda-time 的
DateTime
对象,它是不可变的。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.