Tips & Tricks

Switching between API’s with ease

While you develop and maintain your product, the framework and API on which your product is based on is also being developed and upgraded. This is why the other day you come to a point when you need to switch to a new API. At this time you may already have thousands lines of code where the old API is used.
The good example is migrating from java.util.Vector that was widely used a few years ago to the nonsynchronized ArrayList class. Doing this manually takes hours of work, but of course IntelliJ IDEA can automate and speed up this process.
IntelliJ IDEA provides a tool that helps you with migrating packages and classes. In case of switching between API’s you will also need to make a couple of tricks such as creation of temporary files and some refactoring. Here is the step-by-step instruction:

  1. Create a new class in one of the project packages. This class is temporary and you will need to delete it after migration. The temporary class should have the same name as the class from the old API and extend the class from the new API. For example, when migrating from java.util.Vector to ArrayList, create the temporary Vector class that extends ArrayList.
    Then define all methods lacking or deprecated in the new API but available in the old one.
    In our example, the code will look like below:

    public class Vector extends ArrayList{
    public Object elementAt (int index){
    return get(index);
    }
    }
  2. Migrate the project from the old API to your temporary class using the Refactoring | Migrate command and create a new migration map like shown on the screenshot:
  3. When migrating, you can preview the usages of the old API with the help of the standard IntelliJ IDEA’s Find window.
  4. After migration, in the temporary class, use the Inline refactoring for each defined method. So IntelliJ IDEA will inline all the methods that are not presented in the new API, but possibly used in your code. As a result, you can switch to the new API without any inconsistencies. In our example, there is only one elementAt() method which is inlined.
  5. Use Refactoring | Migrate once again to migrate from your temporary class to the new API class (in our case, from Vector to java.util.ArrayList). Now you can remove the temporary class.

Don’t say it was hard!

Note   This tip&trick was originally posted at www.javalobby.org.

Technorati tags: IntelliJ, IDE, Java
image description