Sobes.tech
Junior — Senior

Refactoring repetitive code in public class methods

livecode

Task condition

In the class SomeClass, there are two public methods (someMethod and someAnotherMethod) that are almost identical. The only difference is the call to different helper functions (doSomething and doAnotherSomethingElse). The task is:

  • Extract the common part into a private method;
  • Replace the duplicated code with calls to the new method;
  • Preserve the original functionality.
public class SomeClass {

    public void someMethod() {
        printCommonPart();
        SomeUtilityClass.doSomething();
        printCommonPart();
    }

    public void someAnotherMethod() {
        printCommonPart();
        SomeUtilityClass.doAnotherSomethingElse();
        printCommonPart();
    }

    private void printCommonPart() {
        System.out.println("do something 1");
        System.out.println("do something 2");
        System.out.println("do something 3");
        System.out.println("do something 4");
    }

    static class SomeUtilityClass {

        static void doSomething() {
            System.out.println("do something");
        }

        static void doAnotherSomethingElse() {
            System.out.println("do something else");
        }

    }
}