Search This Blog

Loading...

Thursday, October 4, 2012

IntelliJ SSR: replace constructors

Suppose you have a large codebase which uses a particular class named SomeClass (nice descriptive name :)). SomeClass has one constructor:

public SomeClass(String a, String b, String c, String d) {
    // Do something
}

This constructor is used at various places in the codebase.

At some point in time an update to SomeClass is made which introduced another constructor:

public SomeClass(String a, String b) {
    // Do something
}


Lets assume you want all calls to the 4 argument constructor to be replaced by the 2 argument constructor. The arguments of the 4 argument constructor should be used in the 2 argument constructor in the following way: new SomeClass(1, 2, 3, 4) becomes new SomeClass(3, 1).

See the following example:


public class UsageOfSomeClass {
    private SomeClass instance_1 = new SomeClass("a", "b", "c", "d");
    private SomeClass instance_2 = new SomeClass("d", "e", "f", "g");
    private SomeClass instance_3 = new SomeClass("h", "i", "j", "k");

    public static void main(String[] args) {
        SomeClass someClass = new SomeClass("1", "2", "3", "4");
    }
}

Should become:

public class UsageOfSomeClass {
    private SomeClass instance_1 = new SomeClass("c", "a");
    private SomeClass instance_2 = new SomeClass("f", "d");
    private SomeClass instance_3 = new SomeClass("j", "h");

    public static void main(String[] args) {
        SomeClass someClass = new SomeClass("3", "1");
    }
}

You can achive the following for an entire codebase with one single structural search and replace action. Use the following templates to achieve this:

Search template: new SomeClass($arg1$, $arg2$, $arg3$, $arg4$)
Replace tempalte: new SomeClass($arg3$, $arg1$)

Hit find and Replace All. Thats it!
Post a Comment