Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Named Parameters in Java another Alternative

DZone's Guide to

Named Parameters in Java another Alternative

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

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.

 

 

 

Using Containers? Read our Kubernetes Comparison eBook to learn the positives and negatives of Kubernetes, Mesos, Docker Swarm and EC2 Container Services.

Topics:

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}