Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance variable vs setter and getter method

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your earnest reply.I got the point Steve.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic