Java overload + vararg pitfall

If you are using overloads In Java, and one of them uses varargs, then there's a rare pitfall to be aware of.

I ran into this a while back. There were two methods, similar to this:

public void method(
        @Nullable Object first,
        @Nullable String second,
        @Nullable Integer third,
        @Nullable BigDecimal fourth,
        @Nullable Double fifth
) throws Exception {

and

public void method(
        @Nonnull Integer... varargs
) throws Exception {

Then, someone added a sixth argument to the first method.

Simultaneously on another branch, someone added a call to the first method like this:

obj.method(null, null, 42, null, null);

Note that combining these is not a merge conflict, but does change the behaviour.

Normally, such simultaneous changes would cause the build to fail, but not in this case: it just switches to the vararg version.

Some notes:

  • Yes, the chance is not very big if many types are involved.
  • Yes, it can also happen for non-vararg overloads, though less likely.
  • It's questionable to have these two overloads, especially if they behave very differently.
  • It might not be a great sign to have methods with many arguments, most of them null.

Comments

No comments yet

You need to be logged in to comment.