Paweł Baczyński wrote:Also, there is no sense in using the String constructor. If you want to assign a String to a variable just write:
Or better yet, simply initialize the object propertyto a default address of "" and forget about conditional logic in the getter entirely.
A getter should be
idempotent. That is, repeated calls to the getter should return the same value (assuming that the property being retrieved hasn't been set by an external function). It should not have any "side effects" (changing its own or other property values) or invoke external functions.
A getter should be low-overhead. In JavaServer Faces, for example, a property might be retrieved up to 6 times (or more) for a single web page request.
A getter, in short, should avoid complicated logic, and especially branching logic, since among other things, that means more complicated
testing is required to validate the property in question when doing unit testing.
This doesn't mean that a getter can only be straight-line value fetch-and-return. In
JSF, I often have getters tied to items pulled from a database. In that case, the first call sees no data, pulls data from the database and then caches it so that subsequent calls don't have to fetch the data again (remember what I said about JSF's multiple invocations of property methods!). Another common case I have is cascaded selection lists - for example, country, state, city, where changing the state has to change the list of available cities. In that case, my state property-change listener invalidates the cache of cities so that the next city property-fetch will go back the the backing store for a new list of cities (which it will then cache).
That may sound like yes, I'm promoting logic in my "get" methods, but the logical effect is the same as a straight fetch, which is what's really important.