Methods

Rule 5:Use varargs Judiciously

// The WRONG way to use varargs to pass one or more arguments!
static int min(int… args) {
if (args.length == 0)
throw new IllegalArgumentException(“Too few arguments”);
int min = args[0];
for (int i = 1; i < args.length; i++)
if (args[i] < min)
min = args[i];
return min;
}
The most serious is that if the client invokes this method with no arguments, it fails at runtime rather than compile time. Another problem is that it is ugly. You have to include an explicit validity check on args, and you can’t use a for-each loop unless you initialize min to Integer.MAX_VALUE, which is also ugly

// The right way to use varargs to pass one or more arguments
static int min(int firstArg, int… remainingArgs) {
int min = firstArg;
for (int arg : remainingArgs)
if (arg < min)
min = arg;
return min;
}

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment