Tips & Tricks

IntelliJ IDEA 8 Refactorings: Wrap Return Value

We’re continuing the series dedicated to new IntelliJ IDEA 8 refactorings. Today’s hero is Wrap Return Value, which is handy when you need to append some data to what a method already returns.
For instance, have a look at the following code.

At the moment we can only retrieve the full person name. Imagine how inconvenient is trying to fish out the separate first or last name in this case. It would be much more convenient if we had an option to retrieve only the part of the name that we need.
Right-click the return value and select Refactor | Wrap Return Value. Specify whether the wrapper should be a new class, an existing one, or an inner class, and click Refactor.
Now the method returns this object instance:

which contains getter for the full name:

Let’s rename the value field to name to make the code more limpid. For that, we’re using Shift+F6 – Rename refactoring. Note that IntelliJ IDEA renames not only the field itself, but the matching getter method as well.
After that, all we need is to just add getters for the first name and last name to the wrapper.

Watch this and the other refactorings in a new live demo!

image description