Named Parameters in Java another Alternative
I wrote before about how you can emulate named parameters in a Java, either using methods or a builder. There is another approach, which already got mentioned in the comments.
On the usage side it looks like this:
-
doSomething4(new ParameterObject() {{
-
name = "Alfred E. Neumann";
-
link = "http://blog.schauderhaft.de";
-
ultimateAnswer = 42;
-
tempFile = "c:\\temp\\x.txt";
-
zip = 23;
-
}});
I find this solution interesting, because it looks seriously weird. At least it did to me when I saw it for the first time, and also to many others who I observed when they encountered it for the first time. So what the heck are we exactly looking at?
-
doSomething4(new ParameterObject() {
-
//…
-
});
Is an anonymous subclass of ParameterObject, which is defined like this
-
class ParameterObject {
-
protected String name;
-
protected String link;
-
protected int ultimateAnswer;
-
protected String tempFile;
-
protected int zip;
-
}
so it is just a bunch of fields. The part that throws many people of is the nested set of {…} it is a java feature that doesn’t get much usage: an initializer. It is similar to a constructor, but can’t take any arguments. It gets executed before any constructor and in this case just sets the fields of the ParameterObject to the desired values.
Appart from the “WTF is this?” effect I don’t find much good things about this approach, especially because it is so confusing for many people. It saves a little typing on the implementor side of the interface I guess, but then you have this new WhatEverStuff() on the client side, which doesn’t help readability much.
Initializers and their siblings static intializers do belong in the toolbox of every java developer though.






Also note that anonymous subclasses with static initializers can break “equals” in some cases (although this is quite unlikely in the ParameterObject scenario): Some implementation of “equals” check for class equality (not instanceof), like
if(this.getClass() == other.getClass())
And maybe yet another drawback: You can just leave out initializing parameters to pass “null” values. This might be confusing because the method call looks different every time. OTOH, developers should be used to different parameter lists.