That javaworld article just seems to be saying that if a field should not be accessible outside the object then adding setters and getters is a bad idea. Of course it is, if people are doing this then they're very very silly.
He doesn't seem to address what, for me, is the main reason to use setters/getters, that is add even more encapsualtion and hiding by protecting the user of the object from it's internal representation. As far as I can tell from the article, he thinks raw field access is OK if the fields are part of the public interface. This causes plenty of problems too when you want to change the internal representation of the object's data. If you have lots of code that goes poking around inside the fields directly then all that code will break if you want to change a field.
This is a similar sin to the one he's trying to avoid. They both come from including things in the public interface that are not necessary and which could change in the future.
The "answer" for me is that fields should never be part of the public interface and for those fields that need to be accessed from outside, you should write public getters/setters so that if those fields ever change their meaning or you change your object from using x,y coordinates to using r, theta then you just have to rewrite getX, setX, getY and setY and all your old code will still work.
Having said that some languages (Perl with lvalue methods, Object Pascal with properties) allow you to have fields that seem to be normal fields but actually they result in a call to a getter/setter method. This to me seems to be the ideal solution. For example in Object Pascal when you write object.Field = 5 you don't know whether that will directly write to memory or whether it will call object.setField(5). What's great here is that the user of a class doesn't need to deal with setters and getters but the implementor get all the advantages that they bring.
Finally he uses the example of getX where the return value changes from an integer to a double and he says that all the code that uses getX will need to change to cope with that. Perfectly true but I don't see how you can blame that on getX. If, instead, you access the X field directly then you're still going to need to change all your code. Seems like a silly example to me. |