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.

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 20 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 22 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: