• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instance variable vs setter and getter method

 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your earnest reply.I got the point Steve.
 
reply
    Bookmark Topic Watch Topic
  • New Topic