Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Fluent API and Code Formatting in NetBeans IDE

DZone's Guide to

Fluent API and Code Formatting in NetBeans IDE

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.

 

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

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.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}