I am quite surprised how unanimous that getters and setters are good and good. I suggest Allen Golub's incendiary article, Getters And Setters Evil . Of course, the name has the meaning of shock, but the author makes the right points.
Essentially, if you have getters and setters for each private field, you make these fields as good as public. It will be very difficult for you to change the type of private field without ripple effects for each class that this getter .
In addition, from a strictly OO point of view, objects must respond to messages (methods) that correspond to their (I hope) common responsibility. The vast majority of getters and setters do not make sense for their component objects, Pen.dispenseInkOnto(Surface) makes more sense to me than Pen.getColor() .
Getters and seters also encourage class users to request an object for some data, perform calculations, and then set a different value in the object, better known as procedural programming. You better just tell the object to do what you are going to do in the first place; also known as Information Expert .
Getters and seters, however, are necessary evils at the layer boundary - UI, persistence, etc. Limited access to internal class classes, such as the C ++ friendship keyword, secure access to Java packages, .NET internal access and the friends class template can help you reduce the visibility of getters and configure only those who need them.
moffdub Sep 19 '08 at 0:13 2008-09-19 00:13
source share