Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

instance variable vs setter and getter method

 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • 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 ?
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • 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 Windows XP Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your earnest reply.I got the point Steve.
 
Villains always have antidotes. They're funny that way. Here's an antidote disguised as a tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic