Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
this is in progress note on why prefer non static method over static

As I said I would always prefer non-static over static method.

  • I am big fan of pure/stateless function,there easy to understand and test, Static method as pure function i.e stateless are not bad but the real problem is to maintain the decipline to keep the 'em stateless.
  • Testablitly: Class B has static method B.foo(), now consider
class A  {

	public void bar() {
		//some important code
		B.foo();// How mock foo bahaviour? may be fiddling classloader with PowerMock but that comes with some bagage too
		//some more important code
		

}
  • Tight coupling : when you use an object inside static methods (you introduced state here).
//consider Class A with instance method a.foo()

and
public Class B {

public static getDesiredCapbilities(String url, String version) {

	//...some code

		a.foo(); //now if you decide you use spring IoC for project, Class B will stand out, Spring can't do any injection for static class and methods.
	//... some code
}
  • It takes away OOPs hence Polymorphism: example: You have a BrowserFactory.createDriver(...) that use Selenium API version 3 to create a web driver, now consider you have two teams A and B. Now consider a new version of it with cool features released. Team B want to upgrade ASAP, team A is busy and want to defer this for couple of months. But now because we have used static methods, we are in one & only one implementation of BrowserFactory else Team would have done this and continued with their code refactoring
//if using spring
//Team A codebase
@Autowire
@Qualifier("version.2.legacy")
private BrowserFactory browserFactory;

//Team B codebase
@Autowire
@Qualifier("version.3")
private BrowserFactory browserFactory;

If not using spring IoC

//if not using spring
//Team A codebase
private BrowserFactory browserFactory = new LegacyBrowserFactory2Impl();

//Team B codebase
private BrowserFactory browserFactory = new BrowserFactoryImpl();

Now static method are good candidate where there is no question of state like verify if number is prime, generate combinations of n list of items, reverse string, join string, compute hash based on params but still as human we make mistake, to prevent it is yet again best to avoid as much as possible relevant factors which in this case is static.

Miško Hevery - http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/ Christian Posta - http://blog.christianposta.com/testing/java-static-methods-can-be-a-code-smell/ Uncle Bob martin -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.