Getter and setter policy

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
 
Having getters and setters is bad as they increase coupling. However if you need to implement them apply the following guides.
 
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. Classes should ideally call their own getter and setters when accessing their internal data. This prevents the object getting into a 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.
+
An object’s data should be encapsulated within itself (protected variables are the closest you will get to achieving this in most languages). Getter and setter methods should be produced for any variable you may consider you have a legitimate reason to declare public. Classes should ideally call their own getters 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]].
 
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]].

Revision as of 15:17, 30 July 2009

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

An object’s data should be encapsulated within itself (protected variables are the closest you will get to achieving this in most languages). Getter and setter methods should be produced for any variable you may consider you have a legitimate reason to declare public. Classes should ideally call their own getters 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.

Personal tools