简体   繁体   中英

If a class has no state, should all the methods be 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?

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 .

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

Make them static when they use no state from an object. Most of it are helper classes like Math. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM