Collecting Parameter
Calculations that gather results from many method invocations need some way to merge those results. One way is to return a value from all of the methods. This works if the value is simple, like an integer.
//Node
int size() {
int result = 1;
for (Node each: getChildren())
result += each.size();
return result;
}
int size() {
int result = 1;
for (Node each: getChildren())
result += each.size();
return result;
}
When merging the results is more complicated than simple addition, it is more direct to pass a parameter that will collect the results. For example, a collecting parameter helps when linearizing a tree:
//Node
asList() {
List results = new ArrayList();
addTo(results);
return results;
}
addTo(List elements) {
elements.add(getValue());
for (Node each: getChildren())
each.addTo(elements);
}
asList() {
List results = new ArrayList();
addTo(results);
return results;
}
addTo(List elements) {
elements.add(getValue());
for (Node each: getChildren())
each.addTo(elements);
}
Some other examples of more-complicated collecting parameters are the GraphicsContext that is passed around a tree of widgets or the TestResult that is passed around a tree of tests in JUnit.
|
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License |
