java - call static method on parameter without instantiating class in argument -


i've been getting tdd , i've started using mockito in junit improve ability test code. i'm loving mockito!

i've noticed have change way think coding, passing collaborators as possible methods , limiting work done in constructors wherever possible.

the following scenario warranted advice experts here on so.

say have method, that's going call static methods on class. e.g.

public void method(){     otherclass.staticmethod(); } 

this bad, it's needed in scenario. make code more testable in unit tests i'd avoid dependency on otherclass , pass argument.

this doesn't work yields compile time error.

public void method(class<? extends otherclass> util){     util.staticmethod(); } ... method(otherclass.class); 

this work, don't instantiating otherclass if don't have to, it's solely class of static utility methods:

public void method(otherclass util){      util.staticmethod(); } ... method(new otherclass()); 

my question you: there better more preferable way accomplish without using new keyword?

this work, don't instantiating otherclass if don't have to, it's solely class of static utility methods:

public void method(otherclass util){      util.staticmethod(); } ... method(new otherclass()); 

actually, doesn't work, invoke method implementation otherclass, irrespective of object pass (even if pass null).

i recommend not use reflection simplify testing, bypasses compile time checking (a wrongly spelled method name not detected compiler), , prevents use of many features of ide (code completion, javadoc hovers, refactoring support, call hierarchy display, jump definition, ...)

the common approach use polymorphic dispatch. in java, requires method not static , not private. rule of thumb therefore is: if needs mocking, shouldn't static.

how best obtain object instance depends on circumstances; dependency injection (your approach), resource locator pattern, , singleton pattern each have own advantages , disadvantages.


Comments