Named Parameters in Java

I lately came across some code that looked like this:

  1. o.doSomething1(
  2.     "Alfred E. Neumann",
  3.     "",
  4.     42,
  5.     "c:\\temp\\x.txt",
  6.     23);

Things were actually worse since there where about 20 or 30 such calls and there was no hint what so ever to the difference in meaning of the various literals.

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

  1. o.doSomething1(
  2.     "Alfred E. Neumann",
  3.     "c:\\temp\\x.txt",
  4.     42,
  5.     "",
  6.     23);

There is no hint that something went wrong. It will compile. And if you are lucky it will blow up once the call executes. But maybe the application will just behave really strange.

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

  1. o.doSomething(
  2.     name = "Alfred E. Neumann",
  3.     link = "",
  4.     ultimateAnswer = 42,
  5.     tempFile = "c:\\temp\\x.txt",
  6.     zip = 23);

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

How about this?

  1. o.doSomething2(
  2.     name("Alfred E. Neumann"),
  3.     link(""),
  4.     ultimateAnswer(42),
  5.     tempFile("c:\\temp\\x.txt"),
  6.     zip(23));

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

  1. public class Name {
  2.     public final String name;
  3.     public Name(String n) {
  4.         name = n;
  5.     }
  6. }

And a static method:

  1. static Name name(String n) {
  2.     return new Name(n);
  3. }

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 before you have to? In that case you should implement hashcode and equals.

There are alternative ways to get similar effects. We’ll look at tehm in another blog post.

  • DZone
  • Digg
  • Reddit
  • Facebook
  • Twitter