Over a million developers have joined DZone.

Fluent API and Code Formatting in NetBeans IDE

DZone's Guide to

Fluent API and Code Formatting in NetBeans IDE

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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
                .setDefaultStyles(null, null, headerStyle, detailStyle)

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//
                .setDefaultStyles(null, null, headerStyle, detailStyle)//

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.


Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}