There are languages like javascript which accept that their functions have a default value. For example:
function times(number = 3, mult = 2) {
return number * mult;
}
times(); // --> 6
times(5); // --> 10
times(undefined, 4); // --> 12
times(5, 3); // --> 15
Is it possible to achieve this behavior in Java?
Although in Java there is no concept as such, the concept of default parameters can implement method overloading , which allows us to have the same method with different parameters.
What should be done is to consider each case:
As you can see, it
times(Double a, double b)
is used when the first argument does not exist, however this is because you are working with a primitive data type. Ideally, the implementation should be similar to this:Another way to achieve the same behavior is with a Fluent Interface , which works similarly to a sequence of setters, only that they return the same object they belong to.
I personally think that the FluentInterface design is much more scalable and useful for this type of case.