bfabry
bfabry

Reputation: 1904

IntelliJ refactoring to inline redundant data class

Is there a sequence of IntelliJ automated refactoring's that will get rid of the superfluous class Foo?

Before refactoring:

  public static class Foo {
    private final String s;
    public Foo(String s) {
      this.s = s;
    }

    public String getS() {
      return s;
    }
  }

  private static void run() {
    Foo f = new Foo("blah");
    f.getS().length();
    f.getS().getBytes();

    Foo f2 = new Foo("blahg");
    f2.getS().length();
    f2.getS().getBytes();
  }

After refactoring:


  private static void run() {
    String f = "blah";
    f.length();
    f.getBytes();

    String f2 = new "blahg";
    f2.length();
    f2.getBytes();
  }

Reason for an automated refactoring in my specific case is the real life Foo is used a few thousand times. But I'm also just interested. It's pretty easy to get a proxy object to the state of Foo using other automated steps, but I just can't figure out how to go the last little bit.

Upvotes: 2

Views: 91

Answers (2)

aaronman
aaronman

Reputation: 18750

A safer way to do this would be to use structural replace

  • search for structural replace in the menu
  • type $Instance$.getS().$MethodCall$($Parameter$) in the search box
  • add a filter on $Instance$ to only be instances of Foo
  • replace with: $Instance$.getS().$MethodCall$($Parameter$)
  • After this you could continue with structural replace and find all instances, and replace them but it's easier to just run Migrate and create a custom type map from class Foo to 'String`
  • if you wanted to use structural replace again you can use something like this for the find and replace
    • Foo $name$ = new Foo($Parameter$);
    • String $name$ = $Parameter$;

Upvotes: 2

pez
pez

Reputation: 1149

Not sure how this would work in a more generic setting, but I would:

  • Refactor Foo to change the name of getS to something very distinct e.g. XXXXXXXXX

  • String replace .XXXXXXXXX() with an empty string

  • Regex stringn replace Foo (\w+) = new Foo\("(\w+)"\); with String $1 = "$2";

This will deal with everything in the run method. Now you just need to manually delete Foo, which while it's not an is not a IntelliJ refactoring, it would only need to be done in one place so might be acceptable.

Upvotes: 2

Related Questions