Saturday, 7 November 2015

Use Varargs Carefully !

So, what are the things need to take care while using varargs in Java ?
Let's take a simple example : 
public static int findMax(int... numbers) {
    int max = numbers[0];
   
for (int i = 1; i < numbers.length; i++) {
       
if (numbers[i] > max)
            max = numbers[i];
    }
   
return max;
}
findMax(1, 2, 3, 4, 5); // 5
findMax(10, 2, 30, 4, 50, 6); // 50
findMax(3); // 3

Here this above code looks good and the findMax() method works fine. But the problem here is in run time it will fail with specific inputs like :
findMax(null); // Exception in thread "main" java.lang.NullPointerException
findMax(); // Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

Because here the code expects at least one value.
So to avoid these problems we can modify the method in such way like :
public static int findMax(int... numbers) {
    if (numbers == null || numbers.length == 0)
       
throw new IllegalArgumentException("At least one input required.");
   
int max = numbers[0];
   
for (int i = 1; i < numbers.length; i++) {
       
if (numbers[i] > max)
            max = numbers[i];
    }
   
return max;
}

But here we need extra code:
#1. one more validation required
#2. the calling method need to be more cautious to handle "IllegalArgumentException"
Instead of all above resolution we can handle this problem in a shorter and smarter way by using the varargs in proper way.

public static int findMax(int firtNumber, int... numbers) {
   
int max = firtNumber;
   
for (int i = 0; i < numbers.length; i++) {
       
if (numbers[i] > max)
            max = numbers[i];
    }
    
return max;
}
Here we have made the first number as a separate parameter, So the compiler will not allow to invoke method by passing null or empty arguments like  findMax(null) and findMax().

No comments:

Post a Comment