考虑到对象封装,getter应该返回一个不可变属性吗? [英] Considering object encapsulation, should getters return an immutable property?

查看:80
本文介绍了考虑到对象封装,getter应该返回一个不可变属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当getter返回一个属性时,例如返回其他相关对象的 List ,该列表及其对象是不可变的,以防止类外的代码,改变那些对象的状态,没有主要的父对象知道?

When a getter returns a property, such as returning a List of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?

例如,如果一个联系对象,有一个 getDetails getter,它返回一个 List ContactDetails 对象,然后调用getter的任何代码:

For example if a Contact object, has a getDetails getter, which returns a List of ContactDetails objects, then any code calling that getter:


  1. 可以从该列表中删除 ContactDetail 对象知道它的联系对象。

  2. 可以更改每个 ContactDetail 对象而不用知道它的联系对象。

  1. can remove ContactDetail objects from that list without the Contact object knowing of it.
  2. can change each ContactDetail object without the Contact object knowing of it.

那么我们该怎么做?我们应该只信任调用代码并返回容易变化的对象,还是为每个可变类创建一个不可变类?

So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?

推荐答案

这是一个问题,你是否应该在你的代码中防守。如果您是您班级的(唯一)用户并且您相信自己,那么无论如何都不需要不可变性。但是,如果此代码无论如何都需要工作,或者您不信任您的用户,那么将外部化的所有内容都变为不可变。

It's a matter of whether you should be "defensive" in your code. If you're the (sole) user of your class and you trust yourself then by all means no need for immutability. However, if this code needs to work no matter what, or you don't trust your user, then make everything that is externalized immutable.

这就是说,大多数属性我创造是可变的。偶尔的用户会把这种情况搞得一团糟,但这又是他/她的错,因为有明确证明突变不应该通过吸气剂接收的可变对象发生。

That said, most properties I create are mutable. An occasional user botches this up, but then again it's his/her fault, since it is clearly documented that mutation should not occur via mutable objects received via getters.

这篇关于考虑到对象封装,getter应该返回一个不可变属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆