Jens Schauder is software developer since 1997. He loves software development for the constant challenges and constantly changing environment. A great chance to learn and teach. He is also blogger, author of various articles and speaker at conferences. Jens is a DZone MVB and is not an employee of DZone and has posted 90 posts at DZone. You can read more from them at their website. View Full User Profile

Named Parameters in Java – an Alternative

  • submit to reddit

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)


Published at DZone with permission of Jens Schauder, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)