Development

Double Brace Initialization

Double brace initialization in Java is a great way to work around APIs that require loads of calls to setters to initialize initial object state.

I needed to create an ATOM feed, and found the ROME jar. This seemed to meet my needs, but I didn’t like the example code.

This from the ROME Wiki

SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(feedType);
feed.setTitle("Sample Feed (created with ROME)");
feed.setLink("http://rome.dev.java.net");
feed.setDescription("This feed has been created using ROME (Java syndication utilities");
List entries = new ArrayList();

SyndEntry entry;
SyndContent description;

entry = new SyndEntryImpl();
entry.setTitle("ROME v1.0");
entry.setLink("http://wiki.java.net/bin/view/Javawsxml/Rome01");
entry.setPublishedDate(DATE_PARSER.parse("2004-06-08"));

description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("Initial release of ROME");
entry.setDescription(description);
entries.add(entry);

This doesn’t feel good at all. Lets ignore all the *Impl*s, and instead take a look at all the setters for setting initial object state.

This code can be made much more readable, and much more succinct by using double-brace initialization

List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndFeed feed = new SyndFeedImpl() {{
    setFeedType("atom_1.0");
    setTitle("Sample Feed (created with ROME)");
    setLink("http://rome.dev.java.net");
    setEntries(entries);
}};
 
entries.add(new SyndEntryImpl() {{
    setTitle("ROME v1.0"");
    setLink("http://wiki.java.net/bin/view/Javawsxml/Rome01");
    setPublishedDate(new Date());
    setDescription(new SyndContentImpl() {{
        setType("text/plain");
        setValue("Initial release of ROME");
    }});
}});

Notice that the object initialization now happens at the time that the object is created, and that you don’t need to create temporary variables all over the place. It is also possible to nest this type of initialization, as shown in the description field.

comments powered by Disqus