Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a class has no state, should all the methods be static?

Tags:

java

oop

static

Lets say I have a Helper class like with a few methods

public class SomeClassesHelperClass(){

    public List removeDuplicatesFromTheGivenList(List someList){
    // code here 
    }

    public int returnNumberOfObjectsThatHaveSomeSpecialState(List someList){
    // code here
    }
}

What are the advantages / disadvantages of making the methods in this class static? Which is the better practice?

like image 780
Koray Tugay Avatar asked Feb 11 '14 13:02

Koray Tugay


People also ask

Should you make all methods static?

Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.

Can all methods of a class be static?

If you have no class level variables, then yes, you can make all the methods on your class static.

Should all methods be static in Java?

We should note that all methods we put in the utility class should be static.

When would you not use a static method?

Static methods can't be used for abstraction and inheritance. You can't declare a static method in an interface or static abstract method in an abstract class. A static method cannot access non-static class level members, not its own, nor its base class.


2 Answers

If your class provides only utility methods (like yours), I believe it's better to:

  • make the class final (there's no point to extend it)
  • define а private constructor to avoid any attempt to create an instance of the class
  • make all the methods static.
like image 164
Konstantin Yovkov Avatar answered Oct 04 '22 20:10

Konstantin Yovkov


If you decide to make all the methods static then you need to be aware of the impact that that will have on your ability to test other classes that depend up on it.

It severely limits your options for mocking ( or at least makes it more painful )

I don't think there is a right answer to our question - it depends on what the methods do. For example, it's easy to envisage a stateless data access object - if you make all its methods static then you are building a dependency on the data source in to your test cycle, or making your mocking code much uglier

like image 38
DaveH Avatar answered Oct 04 '22 20:10

DaveH