Sunday, August 27, 2017

Java: Enforcing a minimum number of method arguments using varargs

Sometimes you need to write a method that requires at least a certain number of arguments. For example, let's say you have a calculation that requires three or more integer arguments. You could write it like this:

public static int calculate(int... args) {
  if (args.length < 3) {
    throw new IllegalArgumentException("At least 3 arguments expected");
  }
  // do something
  return result;
}

The problem with this is that the client cannot tell how many arguments are required and, if they are pass in too few arguments, the method will fail at runtime rather than compile time. You also have to explicity validate the number of arguments passed into the method.

A better way is to declare the method to take 3 normal arguments and 1 varargs arguments, like this:

public static int calculate(int a, int b, int c, int... rest) {
  // do something
  return result;
}

1 comment: