Considering object encapsulation, should getters return an immutable property?

前端 未结 11 505
余生分开走
余生分开走 2020-12-20 11:38

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

11条回答
  •  时光说笑
    2020-12-20 11:57

    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.

提交回复
热议问题