Posts tagged ‘patterns’

Getters and Setters aren’t all they’re cracked up to be

Allen Holub, author of Holub On Patterns, has an interesting article on how if you use getters and setters, you’re probably doing it wrong.

His main claim is that getters and setters are a way of shoehorning procedural design into an object-oriented language, done by people who don’t really understand the difference between a C-style struct and a class. He mentions a course taught in the ’80s by Beck and Cunningham, in which they lament, “the most difficult problem in teaching object-oriented programming is getting the learner to give up the global knowledge of control that is possible with procedural programs, and rely on the local knowledge of objects to accomplish their tasks. Novice designs are littered with regressions to global thinking: gratuitous global variables, unnecessary pointers, and inappropriate reliance on the implementation of other objects.” Holub talks about the CRC design model, in which Classes have Responsibilities and Collaborators. The idea is that the interface to a class should be a list of actions the class can do (its responsibilities) for the other classes it works with (its collaborators). In particular, the interface should not be a list of what data the class can store/retrieve for strangers (which is what getters/setters really are). Under this model, he claims that nearly all getters/setters can be removed in favor of functions that do the work you wanted for you, rather than giving you the info you need to do the work yourself.

Examples, motivations, and discussion →