Preserve Whole Object
From CSSEMediaWiki
(Difference between revisions)
(New page: == 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 n...) |
m (Reverted edits by Ebybymic (Talk); changed back to last version by Aidan Bebbington) |
||
(4 intermediate revisions by 4 users not shown) | |||
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 == | ||
Line 11: | Line 13: | ||
frontWheels = setFrontWheels(frontLeftWheel, frontRightWheel); | frontWheels = setFrontWheels(frontLeftWheel, frontRightWheel); | ||
− | + | turns into a tidier... | |
frontWheels = setFrontWheels(jag); | frontWheels = setFrontWheels(jag); | ||
+ | |||
+ | == See also == | ||
+ | * [[Tell, don't ask]] |
Latest revision as of 03:23, 25 November 2010
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);