A feature that I would like in Java 1.5 that’s not there…

Looking back over the notes from the Dev Day I took, I was reminded of a feature that I would have liked to have seen in 1.5: named parameters.

Named parameters, for those who don’t know, let you do code like this:

map.put( key:foo.getId(), value:foo);

or like this:

 map.put( value:foo, key:foo.getId());

Because you specify the parameter by name, you don’t need to worry about the order. This is particularly useful when you’ve got method definitions like this:

public void doSomething(String, String, String, String, String);

The parameter names help to give a bit of readability, and also to prevent mistakes. Also, as I noted a while back, they let you do things like refactor your code to reorder the parameters; this will become more important with features like the new varargs support.

Unfortunately, named parameters wouldn’t be easy to put into the language. I’m not an expert, but I believe you’d need to change the class file format so that the parameter names in a method are always present; currently, they are only there if you compile with debug turned on. As such, I don’t ever really expect to see them in Java.

So, you look for alternatives. From a code-readability point of view, you can get similar benefits just from using decent names for the parameters (assuming you don’t get the order flat out wrong). From a safety point of view, you can replace generic types (such as Strings) with domain-specific ones; using a Parameter Object can be a step in that direction.

In general, with or without named parameters, methods with a large number of primitives in the parameters are a code smell; it’s just that named parameters reduce the smell somewhat.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s