• Post Reply Bookmark Topic Watch Topic
  • New Topic

Setter and getter  RSS feed

 
Help Me
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone explain the concept behind setter and getter methods ? Where do we use them?

Thanks,
Babu Rajendran
 
John Bartlett
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the reasons is to protect access to the attribute, making the attribute a private and then only allowing access via getter and setter methods restricts users.

e.g. maybe the attribute is only suppose to be readOnly, then by only adding a getter method the class creator can restrict access to that attribute.

Also getters and setters are a good place for validation to be added, e.g. if an int can only set to 1 or more then the user could add the validation to the setter:



Getters and Setters are also used in certain framework patterns, e.g. JSF uses a beans getters and setters to retrieve property values.

Hope this short reply helps,

John
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We see getters and setters in the JavaBean standard and in patterns like Data Transfer Object, and some IDEs will generate them for you. It's easy to think they are a really good idea and put them on every method. But it turns out that "good" objects often hide their state entirely and only expose behavior. You tell objects what to do, but don't ask them for their data. Google for "tell don't ask" and see how much has been written about this.

So that argues against getters. How about setters? It turns out that a lot of "good" objects don't have setters, either. They are "immutable" meaning you can't change their state once they've been created. This is not always the best idea but it's an interesting thing to think about when you start a new class ... can this be immutable?

With promiscuous getters and setters it's tempting to get a few values from an object, do some calculations or logic on them, and set the result back on the object. That's a strong indication that the object should do the work itself and hide all the data from you.

Bottom line: Do not automatically add getters and setters to all your objects. Stop before adding either one and ask if it's really necessary or if you can find a way to make the object do all the work that depends on the state itself.

Does that make sense?
 
Help Me
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! It makes a lot of sense. Thanks a lot!

Regards,
Babu Rajendran
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!