I’ve been reading on reasons why I should and why I shouldn’t use getters and setters. I read this article (A design strategy) on how/why not to use getters and setters but I’m just not “seeing” in what situation I wouldn’t use them or, better yet, an alternative. Yeah, I need to see an alternative to getters and setters.
Share
It’s the second article I read from JW in less that three days and they both share the Why XXXXX is/are evil motto… leaving that behind I think I’ll quote the final words of the article and give my opinion about it.
I believe the author refers to concrete objects, like POJOs (why not entities) that do not interact with anyone. Your site has a login feature, so you have an user… why should you bother with
getNameandsetNameif it’s just aString?While this can be true, what happens if a name is
null? Are you exposing yourself toNullPointerExceptions all around your code? Unless you do a check everytime you use that variable or you make sure no user has anullname you can never be sure. A getter can make it easy, but IMHO it’s all about taste. You’re just moving a check from one place to another.Here, the author seems to be diggin further in the principle of CRC (explained in the article itself), which is a valid argument against most accessors.
Again, it’s all about knowing your application and what will you let the others know about it. I can’t think of an alternative right now, but instead of alternatives I prefer to dig into the concept of Cost VS Benefit, what’s the benefit of avoiding a getter and how much does avoiding it cost to you (time to understand a variable, time to do checks, time to find the field, time to determine and handle the impact of a change where there’s no accessor to limit it).
Another interesting point (and now that I think of it, one of the most important) is WHEN to avoid getters and setters. They’re obviously evil if you expose something you’re not supposed to, like some important variable that holds a counter and can leave your application in an inconsistent state (in other words… “go insane”). In those cases, a getter suffices.
Finally, a lot of frameworks and tools rely in those accessors to set and get values. Avoiding them means losing “compatibility” with those tools… unless you create indirect accessors or wrappers, for example.