📎 Webclip
Printers Instead of Getters
The page argues that getters turn objects into public bags of data and reflect a procedural habit of trusting data instead of the object. It proposes printers as an alternative, so an object produces XML, JSON, or other output itself.
Reading notes#
- Getters and setters are treated as an anti-pattern, and the text says there is no need to keep arguing about that.
- Instead of exposing data through getters, an object should have the ability to print itself to some media.
- A
Bookexample shows the traditional getter approach used with JAXB to produce XML. - The text says this exposes the object’s internals and turns it into a bag of data.
- The convenience of getters is attributed to procedural thinking and to not trusting objects.
- The proposed alternative is a
toXML()printer method on the object itself. - The same idea is extended to
toJSON()when another format is needed. - If many formats are required, the text says the object can become too large.
- To avoid that, it proposes a
Mediaobject that accepts data through aprint(Media media)method. - A
JsonMediaexample shows the media accumulating fields and later producing a JSON object. - The final point is that different media can handle different formats while the
Bookclass stays small.
