aspose file tools*
The moose likes Beginning Java and the fly likes instance variable vs setter and getter method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instance variable vs setter and getter method" Watch "instance variable vs setter and getter method" New topic
Author

instance variable vs setter and getter method

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hi Folkes,



Here[in this DTO class] insteadof using public setter and getter method,make instance variable as public and you can use instance variable right?...i know it is not a good practice but i want to know why everyone use setter and getter method ?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

We use getters and setters because it allows us to do more than just get/set. For example we could do some processing, inform listeners, update back-end data or other local data that relies on the contents of the value being set. It gives the ability to protect the internal storage of the value by making copies when needed and appropriate, and synchronize when an object may be used by multiple threads.

You can add these features as needed without changing client code (the code that uses the DTO) if you use methods. If you allow direct access to the fields and you need to enforce synchronization or inform listeners we either have to rely on client code to synchronize/inform (not safe), or change the interface to our class to use set/get methods, thus breaking client code.


Steve
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Thanks for your earnest reply.I got the point Steve.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: instance variable vs setter and getter method