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

By Robert. Filed in Java  |  
Tags: ,
TOP del.icio.us digg

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:

[source='java']map.put( key:foo.getId(), value:foo);[/source]

or like this:

[source='java'] map.put( value:foo, key:foo.getId());[/source]

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:

[source='java']public void doSomething(String, String, String, String, String);[/source]

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.

Comments are closed.