Sunday, March 11, 2012

Named ranges - a potentially useful concept for Jack (or any normal language)?

Consider the following code that calculates the maximum product of 3 integers possible from a given array (Java used for exposition; could be any language):

public static int maxProd(int[] input){
int max1 = max2 = max3 = java.lang.Integer.MIN_VALUE;
int min1 = min2 java.lang.Integer.MAX_VALUE;
for(int i=0; i<input.length;i++){
// recalc the new max3 numbers
int val= input[i];
if(val > max1){
max2 = max1; // dont lose the old max1
max1=val;
}
else if(val > max2 && val < max1){
max3 = max2; // dont lose the old max2
max2 = val;
}
else if (val > max3 && val < max2) {
max3 = val;
}
// end recalc max
// recalc the min 2 numbers
if(val < min1){
min2 = min1;
min1 = val;
}
else if(val < min2 && val > min1){
min2 = val;
}
// end recalc min
}
view raw gistfile1.java hosted with ❤ by GitHub
The code in the loop could probably be extracted into 2 subroutines but that would involve major interaction between the variables in this one and those subroutines. What if we were able to define the code between the recalc...end recalc comments as a named range that did not introduce a scope? Something like so:

public static int maxProd(int[] input){
int max1 = max2 = max3 = java.lang.Integer.MIN_VALUE;
int min1 = min2 java.lang.Integer.MAX_VALUE;
for(int i=0; i<input.length;i++){
int val= input[i];
range calcmax{
if(val > max1){
max2 = max1; // dont lose the old max1
max1=val;
}
else if(val > max2 && val < max1){
max3 = max2; // dont lose the old max2
max2 = val;
}
else if (val > max3 && val < max2) {
max3 = val;
}
}// end recalc max
range calcMin{
if(val < min1){
min2 = min1;
min1 = val;
}
else if(val < min2 && val > min1){
min2 = val;
}
}// end recalc min
}
view raw gistfile1.java hosted with ❤ by GitHub
IDEs could fold easily on this and this would only help comprehension.

Finally: Why a language construct and not a comment? Because it explicitly aids comprehsnsion. 

1 comment:

vinod said...

Update: I just discovered that C# has had this for ages as Regions