Over a million developers have joined DZone.

Named Parameters in Java – an Alternative

DZone's Guide to

Named Parameters in Java – an Alternative

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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")

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)


Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Published at DZone with permission of Jens Schauder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}