declarative programming
Tom
tbee at tbee.org
Tue Dec 7 00:55:16 PST 2010
Not sure if this is the place to post this, but one has to start somewhere. Since closures will not be part of JDK7 there may be time to hook in one more idea, which uses some of the features introduced by closures; declarative programming.
Basically what declarative programming is, is initializing objects in a readable form. Something like:
Class1 {
property1 = value1;
property2 = Class2 {
property3 = value3;
}
}
This should result in a new instance of class1, that has values for it properties, even if they are other classes.
In Java something similar is somewhat possible using an anonymous constructor, this is "static { }" without the static keyword. For example:
new Class1() {{
property1 = value1;
property2 = new Class2() {{
property3 = value3;
}};
}};
The code above is actual Java code and works, note the {{ }} which create an anonymous inner class and within that an anonymous constructor. There are a few drawbacks though:
- The values must either be constants or final variables. Since this is an anonymous class, referring outside the class to local variables or parameters requires them to be final.
- The property is actually an instance variable which is being access directly.
- The notation is a tad more verbose, requiring "new" and (){{.
I feel that the verboseness should not be a big issue, it is not that much more code. Accessing the property directly is not perfect, but livable. If Java ever decides to introduce an actual @property then that will immediately solve this point. One could also use setters or a combination, but setters reduce readability:
new Class1() {{
setProperty1(value1);
setProperty2( new Class2() {{
property3 = value3;
}});
}};
The choice is to the coder. The biggest issue in fact is the final requirement. If you try to code like this, the amount of finals you have to start spreading through the code is soon going to stop you from continuing. I know that closures have the same problem and that it is being addressed, but I'm not deep enough in to judge if it is feasible to also use that to make this possible.
Any ideas?
Tom
More information about the lambda-dev
mailing list