Inline methods that are only used once

Java pattern

This pattern uses static analysis to find private methods that are only used once, then uses AI to inline them.


Apply with the Grit CLI
grit apply rewrite_simple_functions

Java Class

This Java class has a private method that is only used in one location. We should inline it.

BEFORE
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int multiply(int a, int b) {
        return multiplyHelper(a, b);
    }

    private int multiplyHelper(int x, int y) {
        return x * y;
    }
}

With the rewrite applied, Grit will output:

AFTER
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }
}

Ignore reuse

If a method is used multiple times, it should not be inlined.

JAVA
public class Calculator {
    public String add(int a, int b) {
        return humanize(a + b);
    }

    public String multiply(int a, int b) {
        return humanize(a * b);
    }

    private String humanize(int result) {
        return result.toString();
    }
}