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?
So, you’ve made a complex method a member of an object even though it has
nothinglittle 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: