Over a million developers have joined DZone.

Fluent API and Code Formatting in NetBeans IDE

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

NetBeans IDE's code formatting is really awesome. It does what is expected... in most cases. One weakness is the IDE's treatment of fluent API code blocks. Fluent APIs are all the rage these days with the advent of GroupLayout (which none of us code by hand {and is admittedly not so "these days"}, but nevertheless), FEST, and others like Dynamic Jasper. It's also a cornerstone of the Builder design pattern.

Consider for example a piece of code using Dynamic Jasper:

DynamicReport dr = builder
                .setPageSizeAndOrientation(Page.Page_A4_Landscape())
                .setDefaultStyles(null, null, headerStyle, detailStyle)
                .setUseFullPageWidth(true)
                .build();

It won't do much, but demonstrates the enhanced readability of fluent APIs. Unfortunately, if you press old trusty Alt+Shift+F in the IDE, it will reformat the above to:

DynamicReport dr = builder.setPageSizeAndOrientation(Page.Page_A4_Landscape()).setDefaultStyles(null, null, headerStyle, detailStyle).setUseFullPageWidth(true).build();

Not so clear anymore, right? This is exactly the point of Wilfred Springer in an open letter to Geertjan Wielenga, justifying why he remains loyal to Eclipse. Wilfred's letter contains an excellent example of the usefulness of the fluent API in which form enhances function with indentation. While he will likely remain with Eclipse after this post (my solution doesn't work with the intricate indentation of his example), I have a simple solution for simple cases (look mom, no annotations):

DynamicReport dr = builder//
                .setPageSizeAndOrientation(Page.Page_A4_Landscape())//
                .setDefaultStyles(null, null, headerStyle, detailStyle)//
                .setUseFullPageWidth(true)//
                .build();

Simply add // at the end of each line, and NetBeans IDE will honour your code structure. This is certainly not ground-breaking stuff, but should be handy to people like me, who only discovered it today.

 

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}