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)

Talks

Wan't to meet me in person to tell me how stupid I am? You can find me at the following events: