How to indent the fluent interface pattern "correctly" with eclipse?
Asked Answered
A

1

61

I just created a generator for some fluent interfaces. Now I have lots of code looking like this:

new MyFluentInterface()
    .setFirst( "first" )
    .setSecond( "second" )
    .setThird( "third" )
    .invoke( obj );

I like the indentation shown above, but I can't find a way to configure eclipse to indent this correctly.

eclipse always indents like this:

new MyFluentInterface()
.setFirst( "first" )
.setSecond( "second" )
.setThird( "third" )
.invoke( obj );

How can I configure eclipse so that it indents this fluent interface pattern as shown in my first code example?

Alumna answered 13/11, 2010 at 14:17 Comment(4)
Do you want the formatter to do that? I mean "CONTROL+SHIFT+f" on the whole buffer or do you want to be able to indent only that line?Cioffi
It would be fine if either the formatter or the indenter of eclipse could produce this...Alumna
Hi, I know this is an old thread, have you noticed that Ctrl+A, Ctrl+I undoes this formatting?Wasp
This Ctrl+I thing is annoying as hell :)Quenby
F
74

With Eclipse 3.6, this seems doable by configuring your custom Java > Code Style > Formatter profile. Edit it and go to the Line Wrapping tab and select Function Call > Qualified invocations. Then, in the Settings for qualified invocations, configure things like this:

alt text

This will (should) produce the expected result:

SomeEntity e1 = new SomeEntity.Builder()
    .age(10)
    .amount(10.0d)
    .firstname("foo")
    .lastname("bar")
    .build();

But this will obviously affect all the code, which I personally don't like. So I'm using the new Off/On Tags from Eclipse 3.6 (last tab when editing a profile):

alt text

And enclose the parts that don't get formatted as I want and do it myself:

// @formatter:off
SomeEntity e2 = new SomeEntity.Builder()
    .age(10)
    .amount(10.0d)
    .firstname("foo")
    .lastname("bar")
    .build();
// @formatter:on

Pick your poison :)

Feet answered 13/11, 2010 at 15:55 Comment(6)
@seanizer: Actually, the above is the result of the Builder Pattern Eclipse Plugin. I like this little plugin as it is :)Feet
This didn't work for me. Even after setting this up, the beginning of the "."-lines still match the beginning of the initial lineMacey
At first I didnt think this worked. I found out that it works with auto-format but adding "Correct indentation" to save actions overwrites and pulls it back. Im going to raise an eclipse bug.Benito
I have show whitespace enabled (eclipse.org/forums/index.php/m/249836), and I use off/on tags to create a custom indentation for the different nestings (I'm using a Json builder).Program
@SeanPatrickFloyd you may want to try this one: code.google.com/p/fluent-builders-generator-eclipse-pluginWherry
If it doesn't work ensure there are no compile errors. That stung me for weeks in Eclipse while sorting out formatting issues.Breeden

© 2022 - 2024 — McMap. All rights reserved.