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

Lets say that I have a Helper class, for example, in several ways.

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

What are the advantages / disadvantages of creating methods in this static class? What is the best practice?

+8
java oop static
source share
3 answers

If your class provides only utility methods (like yours), I find it better:

  • make the class final (it makes no sense to extend it)
  • define a private constructor to avoid trying to instantiate a class
  • follow all static methods.
+9
source share

If you decide to make all methods static, then you need to know what effect your ability to test other classes that depend on it will have.

This severely limits your options for bullying (or at least makes it more painful)

I do not think that there is a correct answer to our question - it depends on what the methods do. For example, it is easy to provide an access object without access to data - if you put all its methods into static, then you build a dependency on the data source in your test cycle or make your mocking code much uglier

+2
source share

Make them static if they are not using the state of the object. Most of them are helper classes such as Math. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

+1
source share

All Articles