Getter and setter policy

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(Well there is a starting policy, now we get to decide if it is right.)
m (Reverted edits by Ebybymic (Talk); changed back to last version by Joey Scarr)
 
(10 intermediate revisions by 8 users not shown)
Line 1: Line 1:
Objects should store all their data in private variables. Getter and setter methods should be produced for any variable you might have been tempted to declare public. Classes should ideally call their own getter and setters when accessing their internal data. This prevents the object getting into a invalid state.  
+
Having getters and setters is bad as they increase coupling. However if you need to implement them apply the following guides.
  
Some complications may be encountered when classes contain collections that require non-transactional access.
+
Objects should store all their data in private or protected variables. Getter and setter methods should be produced for any variable you may consider you have a legitimate reason to declare public.  This is supported by the [[Encapsulate concrete state pattern]].  Classes should ideally call their own getter and setters when accessing their internal data. This prevents the object getting into an invalid state. Getters should never return a direct reference to an element contained within the object. Returning a reference in this manner may allow the element to be updated without calling the relevant setter.
 +
 
 +
Generally, if you have too many getters and setters, you should have a closer look at your design to make sure you [[Keep related data and behavior in one place]]. You may also want to consider the [[Tell, don't ask]] design maxim.
 +
 
 +
==See Also==
 +
* [[Getters and setters]]
 +
* [[Minimize accesses to variables]]
 +
* [[Encapsulate concrete state pattern]]
 +
* [[Keep related data and behavior in one place]]
 +
* [[Tell, don't ask]]

Latest revision as of 03:17, 25 November 2010

Having getters and setters is bad as they increase coupling. However if you need to implement them apply the following guides.

Objects should store all their data in private or protected variables. Getter and setter methods should be produced for any variable you may consider you have a legitimate reason to declare public. This is supported by the Encapsulate concrete state pattern. Classes should ideally call their own getter and setters when accessing their internal data. This prevents the object getting into an invalid state. Getters should never return a direct reference to an element contained within the object. Returning a reference in this manner may allow the element to be updated without calling the relevant setter.

Generally, if you have too many getters and setters, you should have a closer look at your design to make sure you Keep related data and behavior in one place. You may also want to consider the Tell, don't ask design maxim.

See Also

Personal tools