Minimize accesses to variables

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
 
Line 5: Line 5:
 
<blockquote>''One way this can be done is to access all variables by sending messages. The data representation can be changed by redefining the accessing messages.''</blockquote>
 
<blockquote>''One way this can be done is to access all variables by sending messages. The data representation can be changed by redefining the accessing messages.''</blockquote>
  
Note that "message" here simply refers to a method call, and consequently an "accessing message" is a getter method.
+
Note that "message" here simply refers to a method call, and consequently an "accessing message" is a getter method. This is similar to Ken Auer's advice of always using getters and setters to access instance variables, even within the class that contains it.
  
Cliffnotes version: ACCESS INSTANCE VARIABLES THROUGH GETTERS, ALWAYS. The only method that should deal directly with a variable is the getter for that variable.
+
Cliffnotes version: ACCESS INSTANCE VARIABLES THROUGH GETTERS, ALWAYS. The only method that should deal directly with a variable is the getter for that variable.  
 +
 
 +
==See also==
 +
* [[Encapsulate concrete state pattern]]
 +
* [[Getters and setters]]
  
 
[[Category: Johnson and Foote's heuristics]]
 
[[Category: Johnson and Foote's heuristics]]

Latest revision as of 01:08, 20 August 2009

The more we can keep our code separate from the underlying data respresentation, the more "abstract" the class is. "Abstract" in this sense means more general, and hence more reusable.

Johnson and Foote recommend getters as a way to increase this separation/generality. In their words:

One way this can be done is to access all variables by sending messages. The data representation can be changed by redefining the accessing messages.

Note that "message" here simply refers to a method call, and consequently an "accessing message" is a getter method. This is similar to Ken Auer's advice of always using getters and setters to access instance variables, even within the class that contains it.

Cliffnotes version: ACCESS INSTANCE VARIABLES THROUGH GETTERS, ALWAYS. The only method that should deal directly with a variable is the getter for that variable.

See also

Personal tools