Considering object encapsulation, should getters return an immutable property?

前端 未结 11 531
余生分开走
余生分开走 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 12:19

    Depends on the context, really. But generally, yes, one should write as defensive code as possible (returning array copies, returning readonly wrappers around collections etc.). In any case, it should be clearly documented.

提交回复
热议问题