Search code examples
javaclassstatichelper

What is the reason helper classes' methods are declared as static?


Why are all the helper classes or utility classes being declared as static?

Is it only for easyness by not creating the instanceof class everytime?

Would static hit the performace badly?

For example:

DateHelper.getCurrentDate();

Solution

  • Because they are not confined to state, they have a single functionality that is purely stateless. For example Math.abs(double a) , it takes a double argument and returns the absolute value. As simple as that. So you dont have to do for example something like

    Math m=new Math();
    m.abs(12.33);
    

    each time to do a simple absolute value calculation which depends only on its argument, using static imposes a simplicity to calling utility methods.

    Edit:- Want to add that there is no performance hit in using static methods. There would only be a lag if the method is static synchronized and mutiple threads want to access it simultaneuously, vs accessing same method (in non static context) in different instances by threads. But most utility methods are atomic in functionality so making them synchronized does not make sense.