Fluent Setters

What are Fluent Setters?

Lately I’ve been making all my setters in bean classes fluent, meaning they return this object and can be chained together.

Take the following bean which exposes a lot of fields.

In order to use this class with it’s default constructor we have to initialize it and then can call all the setters on the object.

This is fine, if a little clunky and spread over several lines.

Alternatively we can create a constructor for all these fields.

Which allows us to instantiate in a single line

Of course you have to remember what order the fields should be added, or get help from your IDE.

But what happens if we want to add another field, say SSN?

Now we have to either introduce another constructor and update our existing one to default the new value to null or else we add a parameter to our existing one and break all the code that relies on it.

But what if we make our setters fluent?

Now we can instantiate our bean in one go, we have no ambiguity as to which field is which and we can add a new field without harming existing code, and of course our setters respect the bean convention and will continue to play nicely with all the frameworks.

Unfortunately setters aren’t generated by the IDE as fluent out of the box, and it can be a bit of a pain to manually change them all, but luckily if you are an IntelliJ user there’s an easy way to create fluent setters.

Creating Fluent Setters in Intellij IDEA

Intellij has a feature called multicursor which lets you use more than one cursor at a time.

In order to place cursors just hold down <shift>+<alt> and click.

Start by placing a cursor at the start of the void keyword in each Setter in the class.

placement

Then hold down <ctrl>+<shift> and hit the right arrow → to select the whole void keyword and type the name of your class followed by a space.

replace_void

Now hit the down arrow ↓ followed by <End> and <Enter> and we can add return this; and our fluent setters are ready for use.

return_this

Couldn’t be simpler, thanks IntelliJ!

What about you, do you already do this, do you have a handier shortcut for creating fluent setters?  Share it in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *