Over a million developers have joined DZone.

Named Parameters in Java

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

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.

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

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