I lately came across some code that looked like this:
o.doSomething1(
"Alfred E. Neumann",
"http://blog.schauderhaft.de",
42,
"c:\\temp\\x.txt",
23);
Things were actually worse since there where about 20 or 30 such calls and there was no hint what so ever to the difference in meaning of the various literals.
Why is so bad? The problem here is that a user of the method doSomething1 might accidently call it with
o.doSomething1(
"Alfred E. Neumann",
"c:\\temp\\x.txt",
42,
"http://blog.schauderhaft.de",
23);
There is no hint that something went wrong. It will compile. And if you are lucky it will blow up once the call executes. But maybe the application will just behave really strange.
Some languages have a feature called named parameters that allows a syntax like this:
o.doSomething(
name = "Alfred E. Neumann",
link = "http://blog.schauderhaft.de",
ultimateAnswer = 42,
tempFile = "c:\\temp\\x.txt",
zip = 23);
Unfortunately Java is not among these languages. But as so often we can trick Java into actually helping us if we are willing to invest in some extra typing.
How about this?
o.doSomething2(
name("Alfred E. Neumann"),
link("http://blog.schauderhaft.de"),
ultimateAnswer(42),
tempFile("c:\\temp\\x.txt"),
zip(23));
It works like this: For every parameter there is a little class:
public class Name {
public final String name;
public Name(String n) {
name = n;
}
}
And a static method:
static Name name(String n) {
return new Name(n);
}
While this is a lot of typing, it gives you some type safety and the equivalence of named parameters. It might also be the first step toward value objects in your code, after all, when you have these values wrapped, why would you unwrap them before you have to? In that case you should implement hashcode and equals.
There are alternative ways to get similar effects. We'll look at tehm in another blog post.
Talks
Wan't to meet me in person to tell me how stupid I am? You can find me at the following events: