Sunday 21 September 2008

Code Review!

Here's the refactorings from my latest code review:

1. Looping over a single collection when searching for matches, avoid nested for loops and use a do while loop instead.

for example the following is a do while loop that checks for matches and performs a rollup:


var i:int = 1;

do {
var dp1:Object = tmp.getItemAt(i - 1) as Object;
var dp2:
Object= tmp.getItemAt(i) as Object;

if (intervalComparisonFunction(dp1, dp2)) {
// they're the same, so delete the previous
tmp.removeItemAt(i - 1);
} else {
// move to the next object in the array..
i++;
}

} while(i <>



2. Use of Closure functions :
Closure
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

For example :

a closure function is passed as an argument,

private static function rollUp(dataPoints:ArrayCollection, intervalComparisonFunction:Function) : ArrayCollection {}

then in the rollUp method body :

if (intervalComparisonFunction(dp1, dp2)) {
// some logic
}



No comments: