Getter and Setter vs. Builder strategy
Posted
by Extrakun
on Stack Overflow
See other posts from Stack Overflow
or by Extrakun
Published on 2010-03-21T18:21:26Z
Indexed on
2010/03/21
18:31 UTC
Read the original article
Hit count: 395
software-engineering
|subjective
I was reading a JavaWorld's article on Getter and Setter where the basic premise is that getters expose internal content of an object, hence tightening coupling, and go on to provide examples using builder objects.
I was rather leery of abolishing getter/setter but on second reading of the article, see to quite like the idea. However, sometimes I just need one cruical element of an entity class, such as the user's id and writing one whole class just to extract that cruical element seems like overkill. It also implies that for different view, a different type of importer/exporter must be implemented (or the whole data of the class to be exported out, thus resulting in waste).
Usually I tend towards filtering the result of a getter - for example, if I need to output the price of a product in different currency, I would code it as:
return CurrencyOutput::convertTo($product->price(), 'USD');
This is with the understanding that the raw output of a getter is not necessary the final result to be pushed onto a screen or a database.
Is getter/setter really as bad as it is protrayed to be? When should one adopt a builder strategy, or a 'get the result and filter it' approach? How do you avoid having a class needing to know about every other objects if you are not using getter/setter?
© Stack Overflow or respective owner