Over a million developers have joined DZone.
Platinum Partner

Named Parameters in Java another Alternative

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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.

 

 

 

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

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 }}