Time and again, when I want to break up a longish Java method into smaller parts, I find myself wishing back the by-reference parameters and access to surrounding local procedure variables of Pascal. Now, I know that the discipline of trying to always pass all required arguments explicitly, and to not rely on changes to by-ref params is often helpful. Nevertheless, sometimes it gets in the way. One fairly clutter free approach to get Pascal's features back goes like this:
public interface LocalBuilder {
T build();
}
and then:While this basically works, it has a few problems:public MyClass computeIt() {
new LocalBuilder() {
final int input1 = ...;
final int input2 = ...;
int state1 = ...;
int state2 = ...;
public MyClass build() {
stepOne();
stepTwo();
return result();
}
private void stepOne() { ... }
private
void stepTwo() { ... }
private
MyClass result() { ... }
}.build();
}
- Exceptions thrown by build() must be declared already on the interface. This is a serious problem.
- For native types such as int, one must provide dedicated interfaces such as LocalIntBuilder with an int build() method, or else go with boxing.
Comments