Skip to content

Instantly share code, notes, and snippets.

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, now consider
class A  {

	public void bar() {
		//some important code;// 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

public Class B {

public static getDesiredCapbilities(String url, String version) {

	//...some code; //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
private BrowserFactory browserFactory;

//Team B codebase
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 - Christian Posta - Uncle Bob martin -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment