[JAVA] Item 53: Use varargs judiciously

53. Variadic arguments should be used with caution

package tryAny.effectiveJava;

public class Varargs {
    public static void main(String[] args) {
        System.out.println(min1(99));
        System.out.println(min2(1, 2, 3));

    }

    // ugly
    static int min1(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;
    }

    // better
    static int min2(int firstArg, int... remainingArgs) {
        int min = firstArg;
        for (int arg : remainingArgs) {
            if (arg < min) {
                min = arg;
            }
        }
        return min;
    }
}
public void foo() { }
public void foo(int a1) { }
public void foo(int a1, int a2) { }
public void foo(int a1, int a2, int a3) { }
public void foo(int a1, int a2, int a3, int... rest) { }

Recommended Posts

Item 53: Use varargs judiciously
Item 52: Use overloading judiciously
Item 45: Use streams judiciously
Item 83: Use lazy initialization judiciously
Item 66: Use native methods judiciously
Item 32: Combine generics and varargs judiciously
Item 55: Return optionals judiciously
Item 26: Don't use raw types
Item 59: Know and use the libraries
Item 40: Consistently use the Override annotation
Item 69: Use exceptions only for exceptional conditions
Item 41: Use marker interfaces to define types
Item 36: Use EnumSet instead of bit fields
Item 71: Avoid unnecessary use of checked exceptions
Item 37: Use EnumMap instead of ordinal indexing
Item 72: Favor the use of standard exceptions
Item 48: Use caution when making streams parallel