Preserve Whole Object

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(Motivation)
Line 2: Line 2:
  
 
When an object passes several data values from a single object as parameters in a method call things can get messy. The problem is that if the object calling the method needs new data values later, then all calls to this method will need to be changed to accommodate this. This problem can be avoided by passing the whole object that you require data from. The called object can then ask for whatever it wants from the whole object. Preserve Whole Object also often makes code more readable.
 
When an object passes several data values from a single object as parameters in a method call things can get messy. The problem is that if the object calling the method needs new data values later, then all calls to this method will need to be changed to accommodate this. This problem can be avoided by passing the whole object that you require data from. The called object can then ask for whatever it wants from the whole object. Preserve Whole Object also often makes code more readable.
 +
 +
Note that this violates [[Tell, don't ask]]
  
 
== Example ==
 
== Example ==

Revision as of 21:31, 14 October 2009

Motivation

When an object passes several data values from a single object as parameters in a method call things can get messy. The problem is that if the object calling the method needs new data values later, then all calls to this method will need to be changed to accommodate this. This problem can be avoided by passing the whole object that you require data from. The called object can then ask for whatever it wants from the whole object. Preserve Whole Object also often makes code more readable.

Note that this violates Tell, don't ask

Example

You need to get several values from an object and pass these values as parameters when calling a method. Send the whole object instead!

frontLeftWheel = jag.getFrontLeft();
frontRightWheel = jag.getFrontRight();
frontWheels = setFrontWheels(frontLeftWheel, frontRightWheel);

turns into a tidier...

frontWheels = setFrontWheels(jag);

See also

Personal tools