Search This Blog

Monday, July 30, 2012

IntelliJ productivity tips


This is the first post in a series of many where I demonstrate a particular feature of IntelliJ. I use IntelliJ on a daily basis and knowing when to use particular features really helps improving productivity. Especially if you just start using IntelliJ you barely scratch the surface of what is possible. These series of posts help to get the most out of the IDE.

An often overlooked but powerful feature in IntelliJ is the structural search and replace. Suppose that there are lots of new instances of a particular class created. Sometimes it is better to use a static factory method instead.

For example: a rather large codebase I was working on had lots of new Integer() statements:

public class SomeClass {
            public static final Integer VARIABLE_1 = new Integer(10);
            public static final Integer VARIABLE_2 = new Integer(20);
            public static final Integer VARIABLE_3 = new Integer(30);
}

If the codebase has 10's, 100's or even 1000's of such statements, you can replace all of them with one single search and replace statement using structural search and replace. In short: with structural search and replace you can search/replace your entire codebase with knowledge about the code.

The above new instance creation can be replaced by doing the following:

  1. Open up the Structural Replace dialog by pressing Ctrl - Shift - M (on Windows) or Command - Shift - M (on OSX)
  2. In the Search template dialog enter the following: new Integer($arguments$)
  3. In the Replacement template enter the following: Integer.valueOf($arguments$)
  4. Make sure you specify java as file type
  5. In the Edit Variables dialog set the minimum and maximum count of the $arguments$ parameter to 1.
  6. The above search template finds all occurrences of new Integer() with exactly one argument and replaces it with Integer.valueOf() taking into account the arguments.
  7. Click find.
  8. In the Find dialog you see all occurrences of new Integer($arguments$) that were found.
  9. Click Do Replace all to replace all new Integer() to Integer.valueOf().
For an in-depth explanation of structural search and replace see http://www.jetbrains.com/idea/documentation/ssr.html.

I hope you enjoy this series. If you have other useful tips please share them!