Named Parameters in Java – an Alternative

In the last installment of this blog I wrote about a way to fake Named Parameters in Java. As so often there are many ways to do this, so here comes another one.

Instead of static methods producing value objects for each parameter you can use a single parameter object that happens to be a builder:

The method signature would look like this:

  1. void doSomething3(ParameterBuilder pb)

The usage looks like this:

  1. doSomething3(new ParameterBuilder()
  2.     .name("Alfred E. Neumann")
  3.     .link("http://blog.schauderhaft.de")
  4.     .ultimateAnswer(42)
  5.     .tempFile("c:\\temp\\x.txt")
  6.     .zip(23)
  7. );

and the builder itself like this:

  1. public class ParameterBuilder {
  2.  
  3.     private String link;
  4.     private String name;
  5.     private int answer;
  6.     private int zip;
  7.     private String file;
  8.  
  9.     public ParameterBuilder name(String aName) {
  10.         name = aName;
  11.         return this;
  12.     }
  13.  
  14.     public ParameterBuilder link(String aLink) {
  15.         link = aLink;
  16.         return this;
  17.     }
  18.  
  19.     public ParameterBuilder ultimateAnswer(int anAnswer) {
  20.         answer = anAnswer;
  21.         return this;
  22.     }
  23.  
  24.     public ParameterBuilder zip(int aZip) {
  25.         zip = aZip;
  26.         return this;
  27.     }
  28.  
  29.     public ParameterBuilder tempFile(String aFile) {
  30.         file = aFile;
  31.         return this;
  32.     }
  33.  
  34.     // … getters for the fields omitted.
  35. }

In a sense this is even more similar to named parameters, since you can define default values in the builder, thereby making arguments optional. Also the order of arguments does not matter.

If you want to use the parameter object for more then transfering a bunch of values from one side of a method signature to the other you should consider actually creating an immutable object from you builder (or at least passing it as an implementation of an immutable interface)

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter