DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • AI’s Role in Everyday Development
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  1. DZone
  2. Coding
  3. Java
  4. Functional Default Arguments, Part One

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.

By 
Federico Peralta Schaffner user avatar
Federico Peralta Schaffner
·
Aug. 22, 16 · Tutorial
Likes (20)
Comment
Save
Tweet
Share
54.1K Views

Join the DZone community and get the full member experience.

Join For Free

Outline

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.

Java (programming language) Anti-pattern Builder pattern Java language Functional programming Cons POST (HTTP) Scala (programming language) Extract

Published at DZone with permission of Federico Peralta Schaffner, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!