Tuesday, November 16, 2010

Java Beans - getters and setters- how you see them

When we talk about Java Beans. Thing comes to the mind is an object having only getters and setters to access and change its instance variables. A POJO. Ever thought why do we use this or are they really useful in your project? Maybe we are using them because its a standard but not a need. Maybe we do need them. Let me dive into its depth.

If my service layer has to transfer some data between data layer and other layers. I would go for a DTO which is a class with private instance variables and respective setter and getters which will change them when needed. Some time I as a question to my self that if I am providing getter and giving the object to the caller and setter which will change the instance variable, then why do I keep it private. Don't you think I should make that object with all public fields without any setters or getters. This will also reduce the lines of code and easy to acess the instance variables.
If this is the case, then why am I providing getXXX() and setXXX (). Is it just that its a standard and I have to follow?