Search code examples
javaintellij-idearefactoringautomated-refactoring

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.


Solution

  • 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.