Skip to main content

Posts

Showing posts from 2016

What is the purpose of accessors?

Can somebody help me understand the  get  &  set ?  Why are they needed? I can just make a public variable. What  are  properties? Properties are language elements that allow you to avoid the repetitive  getXYZ()  accessors and  setXYZ()  mutators techniques found in other languages, like Java. Why do they exist? They aim to solve the following problems: Saying  get  and  set  in the beginning of every access or mutation of a value is annoying and distracting. In Java, you often say: class person { private int _age ; public void setAge ( int value ) { /*check value first, then set _age*/ } public int getAge () { return this . _age ; } } and then consistently say: if ( person . getAge () > blah || person . getAge () < 10 ) { person . setAge ( 5 ); } After a while, the  get  and  set  become rather annoying. Providing direct access to the actual variable breaks encapsulation, so that's not an option. H