Platinum Partner
java,tips and tricks

Named Parameters in Java another Alternative

I wrote before about how you can emulate named parameters in a Java, either using methods or a builder. There is another approach, which already got mentioned in the comments.

On the usage side it looks like this:

  doSomething4(new ParameterObject() {{
        name = "Alfred E. Neumann";
        link = "http://blog.schauderhaft.de";
        ultimateAnswer = 42;
        tempFile = "c:\\temp\\x.txt";
        zip = 23;
    }});

I find this solution interesting, because it looks seriously weird. At least it did to me when I saw it for the first time, and also to many others who I observed when they encountered it for the first time. So what the heck are we exactly looking at?

        doSomething4(new ParameterObject() {
     //…
     });

Is an anonymous subclass of ParameterObject, which is defined like this

  class ParameterObject {
        protected String name;
        protected String link;
        protected int ultimateAnswer;
        protected String tempFile;
        protected int zip;
    }

so it is just a bunch of fields. The part that throws many people of is the nested set of {…} it is a java feature that doesn’t get much usage: an initializer. It is similar to a constructor, but can’t take any arguments. It gets executed before any constructor and in this case just sets the fields of the ParameterObject to the desired values.

Appart from the “WTF is this?” effect I don’t find much good things about this approach, especially because it is so confusing for many people. It saves a little typing on the implementor side of the interface I guess, but then you have this new WhatEverStuff() on the client side, which doesn’t help readability much.

Initializers and their siblings static intializers do belong in the toolbox of every java developer though.

 

 

 

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}