Reputation: 23800
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?
Upvotes: 12
Views: 3344
Reputation: 62864
If your class provides only utility methods (like yours), I believe it's better to:
final
(there's no point to extend it)private
constructor to avoid any attempt to create an instance of the classstatic
.Upvotes: 10
Reputation: 7335
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
Upvotes: 4
Reputation: 2085
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
Upvotes: 1