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

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

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.


Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}