Thursday, July 16, 2009

Java Double Brace Initialization

refactory.com refactory.org describes one of my favorite Java tricks: double brace initialization. Double brace initialization is an extension of creating an anonymous inner class. The inner brace is a static initialization block. It will get invokes when the object is initialized.

refactory.com lists UI class instantiation as an application for double bracing. It's been ages since I've used Swing for anything, but I remember anonymous inner classes were very helpful for making tweaks to the Swing classes.

For a brief example consider the following Foo.java.

Foo foo = new Foo() {
{
// static initialization block
this.setBar(100);
}
// overridden and new methods
public void setBar(int bar) {
if (bar < 0 || bar >100) {
// ignore input that is out of range
return;
}
this.bar = bar;
}
};


Double bracing can be very helpful for writing test code. The static initialization block can set up an object in a state that is relevant to the test and the relevant methods of the class can be overridden to support the test.

3 comments:

aaron said...

Small correction: the site is refactory.org, not refactory.com

Paul Wiedel said...

Aaron, sorry about that. Thank you for the correction.

info said...

Javas Double Brace Instatiation makes it a lot easier to read your source code. For review reasons is that important to you and your colleagues. I think most people only see these advantages if nobody uses them: they would be glad to have them.

A few tips and backgrounds, too: is is about the obstacles and the possibillities with Javas Double Brace Instatiation:
http://bit.ly/endUIi

I hope I could help a little.