views:

79

answers:

2

A small debate flared up in a question about protected member variables regarding the use of getters/setters. There are lots of questions already over whether getters/setters are evil, however one particular argument against them, which was posed by two separate individuals with much higher reputation than myself, struck me.

One said that getters/setters made the code only 0.01% less brittle, and the other stated that adding 10 lines of code where one would do makes the code more brittle.

This goes against most of what I had previously read, been taught, thought, or experienced. Does anyone else agree/disagree with those comments?

A: 

It depends. If your getters/setters are simple and straightforward, ie you get the value and set the value and no other manipulation, I just don't see how it can make the code more brittle.

In contrast, if you are manipulating the value, say, perhaps you trim the string before setting it, or you run through a formatter before return the value, then I would say, "perhaps"... but then, this is where testcases come in to ensure they are properly tested, AND you should document it properly in Javadoc so that the callee knows the expected outcome when making the calls.

When someone use the word "brittle", it comes across my mind that if it will easily break something in the future. By just introducing getters/setters don't neccessarily make the code brittle. Perhaps, you can just use Groovy then so you don't actually see these assessor methods. :)

limc
+1  A: 

I know it is close to herecy, but I hate get/set methods. Loathe them. Almost never write them.

Generally, a class should either provide much more high-level operations than directly and simply reading and modifying internal state variables, or it should get the hell out of the way and act like the struct it is.

Even if I were to write one, I would almost never use it inside the class. The whole point of them is that you can change the internal representation of thing without affecting a client. Inside the class, it is the internal representation you care about! If you are tempted to do a lot of operations on the class using its own interface inside the class, you probably have a second class in there fighting to get out.

T.E.D.
Just for fun, this answer is a repeat of my answer in http://stackoverflow.com/questions/2374009/calling-this-get-this-set-methods-versus-directly-accesing-member-variables-in/2374139#2374139. I'm curious what the result will be.
T.E.D.