Bookmark Topic Watch 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
What are "accessor methods"?

Accessor methods (also called getters/setters) are methods which encapsulate the access to fields of an object.









Why don't I just access the fields directly?

There are several reasons why this would probably be a not-so-good idea:


  • An object should have full control over its data. With direct field access, it doesn't know when a value gets changed and can't react accordingly. You might later want to cache some data, lazily initialize it, calculate it on the fly instead of putting it into a field, notify someone of a change or a myriad of other things. Without accessor methods, you don't have a place to put that behaviour.


  • (Some languages make it possible to switch from direct access to access through methods without the clients even noticing. Java doesn't, so it's often quite costly to do that switch later.)


  • Fields aren't polymorphic. If you later want to make use of polymorphic behaviour - for example getting a value from a different source in a subclass, or applying the DecoratorPattern - you can't do so with direct field access.



  • As someone else might expand on, good ObjectOriented design and experienced ObjectOriented developers suggest that developing message- and behavior-based systems is a good thing.


  • So, should I have AccessorMethods for all my fields?


  • Uh, no. Sometimes you don't need 'em (see Wiki:YouAintGonnaNeedIt) and sometimes it isn't appropriate to allow outsiders access to your state (see above).


  • What about field access in the class itself? In Subclasses?

    Related threads:


  • https://coderanch.com/t/98276/patterns/Getter-Setter-Methods
  • https://coderanch.com/t/98435/patterns/getters-setters-evil


  • Other resources:


  • Wiki:AccessorsAreEvil
  • http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?

  •  
    I'm just a poor boy, I need no sympathy, because I'm easy come, easy go, little high, little low, little ad
    Gift giving made easy with the permaculture playing cards
    https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
      Bookmark Topic Watch Topic
    • New Topic