Over a million developers have joined DZone.

Named Parameters in Java

DZone 's Guide to

Named Parameters in Java

· Java Zone ·
Free Resource

I recently came across some code that looked like this:

        "Alfred E. Neumann",

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:

        "Alfred E. Neumann",

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:

        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?

        name("Alfred E. Neumann"),

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.

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}