Functional Default Arguments, Part One
The most widely-known workaround for defining default arguments for methods and constructors in Java uses method overloading, though varargs, null values, the builder pattern, and even maps have been used as well. Here we propose a new approach based on functional constructs.
Join the DZone community and get the full member experience.
Join For FreeOutline
Java lacks a built-in way to define default arguments for methods and constructors. Over the years, several approaches have been proposed, each with its pros and cons. The most widely-known one uses method overloading, though varargs, null values, the builder pattern, and even maps have been used as well. Here we propose a new approach based on functional constructs.
Functional Default Arguments
Background
Many languages support default arguments for methods and constructors out of the box, i.e. Scala:
def sum(x: Int = 6, y: Int = 7): Int = x + y
The sum method can be invoked as follows:
sum(1, 2) // 3 -> x = 1, y = 2 (no defaults)
sum(3) // 10 -> x = 3, default y = 7
sum(y = 5) // 11 -> default x = 6, y = 5
sum() // 13 -> default x = 6, default y = 7
sum(y = 3, x = 4) // 7 -> x = 4, y = 3 (no defaults)
This is very handy, but Java doesn't support it. There are a few different ways to accomplish something similar, however all of them have some drawback.
Method Overloading
The most widely-known one uses method overloading to simulate default arguments:
public int sum(int x, int y) {
return x + y; // actual implementation
}
public int sum(int x) { // default y = 7
return this.sum(x, 7);
}
public int sum() { // default x = 6
return this.sum(6); // and y = 7 (implicitly)
}
Despite this is a very common pattern (or anti-pattern) in Java, it has some drawbacks:
- The number of overloads for the method increases exponentially with the number of arguments, since all possible, meaningful argument combinations must be considered.
- Some argument combinations are not possible because overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the example above, there's no way to define an overload sum(int y) that defaults the value of x, because we have chosen to specify x as an explicit argument (defaulting y to 7).
- Definition of default argument values is implemented inside the overloaded methods, thus making defaults global to every caller. In other words, this does not take the method invocation's context into account.
Varargs
Another approach to default arguments in Java is using varargs:
public int sum(int... arguments) {
// Define default values
int x = 6;
int y = 7;
// Extract explicit argument values, checking bounds
if (arguments != null && arguments.length >= 1) {
x = arguments[0];
if (arguments.length >= 2) {
y = arguments[1];
}
}
return x + y;
}
Here we define the default values and then extract the explicit arguments from the varargs parameter. Each default value is preserved only if its corresponding explicit value is not present in the varargs parameter.
Drawbacks of this approach are:
- As per the Java Language Specification, varargs parameters must be specified at the end of the argument list.
- If default arguments were of different types, the varargs parameter definition should be changed to Object... arguments. But if we do this, we lose static type checking, so we would have to check each argument's type at runtime, cast it and handle all possible errors...
- Both definition of default argument values and handling of the varargs parameter are to be implemented inside the method. As with the method overloading approach, defaults remain global to every caller, so the method invocation's context is not taken into account.
Null values
This approach is quite simple: if you invoke the method with a null argument, then its corresponding default value is used instead:
public int sum(Integer x, Integer y) {
// Define default values
x = x == null ? 6 : x;
y = y == null ? 7 : y;
return x + y;
}
Using null values is much simpler than previous approaches. However it still has some drawbacks:
- As null is to be used to specify a default value, it cannot be used as an argument's valid explicit value.
- Primitives are not allowed, since only references can be null. This is why we've used wrapper types in the example above.
- Checking for null arguments and assigning default values has to be implemented inside the method. Again, defaults remain global to every caller, so the method invocation's context is not taken into account.
Other Approaches: Maps, Optional, and the Builder Pattern
In this StackOverflow answer given by user Vitalii Fedorenko, all common approaches to default arguments are visited. I won't analyze them here, since there are already a lot of articles that explore their pros and cons. Instead, I would like to introduce a new way to work with default arguments in Java that takes functional programming into consideration. But that will have to wait until the second part of this article...
Sign Up for the Newsletter
Did you enjoy this post? If so, stay tuned for part two tomorrow, and please consider signing up to The Bounds of Java newsletter. I usually write a new post every 2-4 weeks, so if you'd like to be kept in the loop for the next one, I'd really appreciate it if you'd sign up.
Published at DZone with permission of Federico Peralta Schaffner, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments