Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Static method and variables - Good vs Bad

I am developing C# and asp.net web application.

I have general class called utilities, I have lot of public and static variables in this public utilities class.

Since this number is gradually increasing, I want to know is it good practice to store utilities methods and variable as public static.

Example of my code

public class utilities
{
    public static string utilVariable1 = "Myvalue";
    public static string utilVariable2 = "Myvalue";
    public static string utilVariable3 = "Myvalue";
    :
    public static string utilVariableN = "Myvalue";


    public static string UtilMethod1()
    {
         //do something
    }

    public static string UtilMethod2()
    {
         //do something
    }

    public static string UtilMethodN()
    {
         //do something
    }
}
like image 634
Shruti Sharma Avatar asked Sep 08 '11 10:09

Shruti Sharma


1 Answers

There's nothing inherently wrong with static classes, although they should typically not have state (fields). Your use of public static fields indicates that this is not the case, so it seems like you are using abusing the static keyword slightly. If your class needs to have state, then it should be a normal, non-static class, and you should create instances of it. Otherwise, the only public fields visible on the class should be const (consider the Math class, with constants such as Math.PI - a good use of static methods and fields).

Another consideration is cohesion. Methods typically exist grouped in one class because they are closely related in one way or another. Again, the Math class is a good example; everything in there has to do with maths. At some point, you would want to split your global utility class into multiple smaller, more focussed ones. See Wikipedia for some examples on cohesion, it sounds like your usage falls under "Coincidental cohesion (worst)".

like image 165
Daniel B Avatar answered Nov 11 '22 23:11

Daniel B