Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding static methods to facilitate cleaner unit tests - good practice?

Say I have this class:

class MyClass {
    private String s;
    // more attributes here
    public MyClass(String s, /*more constructor params*/)  {...}

    public String myMethod(String s) {
        //complex logic here
    }
}

To unit test myMethod() I need to create the entire object (with many parameters that need constructed, etc), while the method only uses s.

Altenatelly I can add a static method:

class MyClass {
    private String s;
    // more attributes here
    public MyClass(String s, /*more constructor params*/)  {...}

    public String myMethod(String s) {
        return myStaticMethod(s);
    }

    public static myStaticMethod(String s) {
        //complex logic here
    }
}

Now I can easily test "complex logic" without the need to create the object. someStaticMethod(String s) should have no side-effects on the class. So I am adding an extra method just for the ease of testing. Is this a good practice?

like image 570
Adrian Avatar asked Jan 28 '26 06:01

Adrian


1 Answers

So, you've made a complex method a member of an object even though it has nothing little to do with that instance?

Yes, I agree you should use a different design. It could be a static method in that class, or factored into its own class. Or it might be a method of an object that implements a "Strategy" pattern. The right decision depends on the potential for change.


Maybe something like this:

class ComplexLogician {

  String myMethod(String a, String b) {
    /* Complex logic here. */
  }

}

class MyClass {

  private String s;

  private final ComplexLogician logic;

  /* More attributes here... */

  MyClass(String s, ComplexLogician logic, /* More parameters... */)  {...}

  String myMethod(String b) {
    return logic.myMethod(s, b);
  }

}
like image 146
erickson Avatar answered Jan 30 '26 20:01

erickson