Named parameters
The "treat-array-elements-as-pairs' design pattern
can be used to simulate named parameters in Java. The VarArgs class
provides support to accomplish this.
Using this class, you can write the following:
import sugar4j.lang.VarArgs;
class Person {
Person(Object... attributes) { // declare an Object varargs parameter
VarArgs args = new VarArgs(attributes); // construct a VarArgs instance, passing the array
// those are required // access members using get(). No casts necessary
id = args.get("id");
name = args.get("name");
lastName = args.get("lastName");
// title is optional
title = args.get("title", null);
}
String name;
String lastName;
int id;
String title;
}
Person is then initialized like this:
Person krizz = new Person("id", 23, "name", "Christian", "lastName", "Oetterli", "title", "Mr.");
This is a demonstration that named parameters are possible, easy and even fairly readable with the current Java language constructs.
We do not generally recommend using this class since those "soft-string-references" circumvent the static type checking capabilities of the Java compiler. |