Definition Of A Helper Class – The Best Way

Sometimes functionality needs to be global and grouped together, without no direct relationships to objects.  In these cases I create helper classes.  I have my own way of doing such, but I see other developers during a variation on the same theme in not so optimal way.

Let’s take the “bad” solutions one at a time:

Static methods (“Poor mans helper method”)

OK, the intention is good however the definition gives the user the impression of being able to create an instance of the class (and actually possible to do so) without the need for such.

 

    public class HelperClass
    {
        public static void MyMethod(){}
    }

Better (“Hide an seek”)

Preventing the construction of a helper class, when no need for constructing such – is a good step.
However imagine opening the source file for this helper class and that the helper class has a lot of fields and properties, and the constructor is placed several pages down in the file.  Then you won’t directly and quickly be able to tell, if the class needs to be constructed.

 

    public class HelperClass
    {
        private HelperClass(){}

        public static void MyMethod(){}
    }

Abstracting it

Marking the helper class as abstract, of course deals with the problem of not being able to create the class.  Doesn’t introduce an unnecessary empty private constructor.  However this gives the impression of, that someone is going to implement the class.  So by far a good solution.

 

    public abstract class HelperClass 
    { 
        public static void MyMethod(){} 
    } 

My Method – Going Completly Static

Marking the class as static, quickly denotes:  No derrivation and only static methods in the class.
So this is in my opinion, the best syntax for creating helper classes.

 

    public static class HelperClass 
    { 
       public static void MyMethod(){}  
    }