Considering object encapsulation, should getters return an immutable property?

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

    When I was starting out I was still heavily under the influence of HIDE YOUR DATA OO PRINCIPALS LOL. I would sit and ponder what would happen if somebody changed the state of one of the objects exposed by a property. Should I make them read only for external callers? Should I not expose them at all?

    Collections brought out these anxieties to the extreme. I mean, somebody could remove all the objects in the collection while I'm not looking!

    I eventually realized that if your objects' hold such tight dependencies on their externally visible properties and their types that, if somebody touches them in a bad place you go boom, your architecture is flawed.

    There are valid reasons to make your external properties readonly and their types immutable. But that is the corner case, not the typical one, imho.

提交回复
热议问题