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

Named Parameters in Java

DZone's Guide to

Named Parameters in Java

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

I recently came across some code that looked like this:

    o.doSomething1(
        "Alfred E. Neumann",
        "http://blog.schauderhaft.de",
        42,
        "c:\\temp\\x.txt",
        23);

Circumstances were actually worse because there were about 20 or 30 such calls like that. I found not a single hint to the difference in meaning of the various literals.

Why is this so bad? The problem here is that a user of the method doSomething1 might accidently call it with:

  o.doSomething1(
        "Alfred E. Neumann",
        "c:\\temp\\x.txt",
        42,
        "http://blog.schauderhaft.de",
        23);

We can't tell if something went wrong. Compilation will occur. If you're lucky, it will blow up once the call executes. Maybe the application will behave oddly, for instance.

Some languages have a feature called named parameters that allows a syntax like this:

o.doSomething(
        name = "Alfred E. Neumann",
        link = "http://blog.schauderhaft.de",
        ultimateAnswer = 42,
        tempFile = "c:\\temp\\x.txt",
        zip = 23);

Unfortunately, Java is not among these languages. Very often we can trick Java into actually helping us if we are willing to invest in some extra typing.

How about this?

o.doSomething2(
        name("Alfred E. Neumann"),
        link("http://blog.schauderhaft.de"),
        ultimateAnswer(42),
        tempFile("c:\\temp\\x.txt"),
        zip(23));

It works like this: For every parameter there is a little class:

public class Name {
        public final String name;
        public Name(String n) {
            name = n;
        }
    }

And a static method:

 static Name name(String n) {
        return new Name(n);
    }

While this is a lot of typing, it gives you some type safety and the equivalence of named parameters. It might also be the first step toward value objects in your code. After all, when you have these values wrapped, why would you unwrap them early? Implement hashcode and equals if you need to do that.

We do have alternative ways to get similar effects—we’ll look at them in another blog post.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}