What should be allowed inside getters and setters?

Posted by Botond Balázs on Programmers See other posts from Programmers or by Botond Balázs
Published on 2012-11-25T19:42:01Z Indexed on 2012/11/25 23:21 UTC
Read the original article Hit count: 363

I got into an interesting internet argument about getter and setter methods and encapsulation. Someone said that all they should do is an assignment (setters) or a variable access (getters) to keep them "pure" and ensure encapsulation.

  • Am I right that this would completely defeat the purpose of having getters and setters in the first place and validation and other logic (without strange side-effects of course) should be allowed?
  • When should validation happen?
    • When setting the value, inside the setter (to protect the object from ever entering an invalid state - my opinion)
    • Before setting the value, outside the setter
    • Inside the object, before each time the value is used
  • Is a setter allowed to change the value (maybe convert a valid value to some canonical internal representation)?

© Programmers or respective owner

Related posts about object-oriented

Related posts about language-agnostic