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.
Talks
Wan't to meet me in person to tell me how stupid I am? You can find me at the following events: