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!

This entry was posted in Tips & Tricks. Bookmark the permalink.

One Response to IntelliJ IDEA 8 Refactorings: Wrap Return Value

  1. A wonderful refactoring, but a misleading example. If I have a getter for a class member and would like to refactor the return value .. won’t the refactoring “Type Migration” even better to use? OK, this one would not create the new class, but it converts the getter, a hopefully existing setter and the type of the class member.

Leave a Reply

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