Over a million developers have joined DZone.

Named Parameters in Java – an Alternative

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

In the last installment of this blog I wrote about a way to fake Named Parameters in Java. As so often there are many ways to do this, so here comes another one.

Instead of static methods producing value objects for each parameter you can use a single parameter object that happens to be a builder:

The method signature would look like this:

void doSomething3(ParameterBuilder pb)

The usage looks like this:

 doSomething3(new ParameterBuilder()
        .name("Alfred E. Neumann")
        .link("http://blog.schauderhaft.de")
        .ultimateAnswer(42)
        .tempFile("c:\\temp\\x.txt")
        .zip(23)
    );

and the builder itself like this:

    public class ParameterBuilder {
     
        private String link;
        private String name;
        private int answer;
        private int zip;
        private String file;
     
        public ParameterBuilder name(String aName) {
            name = aName;
            return this;
        }
     
        public ParameterBuilder link(String aLink) {
            link = aLink;
            return this;
        }
     
        public ParameterBuilder ultimateAnswer(int anAnswer) {
            answer = anAnswer;
            return this;
        }
     
        public ParameterBuilder zip(int aZip) {
            zip = aZip;
            return this;
        }
     
        public ParameterBuilder tempFile(String aFile) {
            file = aFile;
            return this;
        }
     
        // … getters for the fields omitted.
    }

In a sense this is even more similar to named parameters, since you can define default values in the builder, thereby making arguments optional. Also the order of arguments does not matter.

If you want to use the parameter object for more then transfering a bunch of values from one side of a method signature to the other you should consider actually creating an immutable object from you builder (or at least passing it as an implementation of an immutable interface)

 

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

Published at DZone with permission of Jens Schauder , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}