Considering object encapsulation, should getters return an immutable property?

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

    Your first imperative should be to follow the Law of Demeter or ‘Tell don't ask’; tell the object instance what to do e.g.

    contact.print( printer ) ;  // or
    contact.show( new Dialog() ) ; // or
    contactList.findByName( searchName ).print( printer ) ;
    

    Object-oriented code tells objects to do things. Procedural code gets information then acts on that information. Asking an object to reveal the details of its internals breaks encapsulation, it is procedural code, not sound OO programming and as Will has already said it is a flawed design.

    If you follow the Law of Demeter approach any change in the state of an object occurs through its defined interface, therefore side-effects are known and controlled. Your problem goes away.

提交回复
热议问题