使用静态方法和变量 - 好VS坏 [英] Using Static method and variables - Good vs Bad

查看:198
本文介绍了使用静态方法和变量 - 好VS坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发C#和asp.net web应用程序。



我一般类中调用事业,我有很多在这个公共事业类公共和静态变量。



由于这个数目也逐渐增多,我想知道的是它来存储公用设施的方法和变量作为公共静态好的做法。



我的代码示例

 公共类公用事业
{
公共静态字符串utilVariable1 =myvalue的;
公共静态字符串utilVariable2 =myvalue的;
公共静态字符串utilVariable3 =myvalue的;

公共静态字符串utilVariableN =myvalue的;


公共静态字符串UtilMethod1()
{
//做些什么
}

公共静态字符串UtilMethod2()
{
//做些什么
}

公共静态字符串UtilMethodN()
{
//做些什么
}
}


解决方案

有什么本质上错与静态类,尽管他们通常应该不会有状态(字段)。您使用公共静态的字段表明这是不是这样的,所以它好像你正在使用滥用静态关键字咯。如果你的类需要有状态,那么它应该是一个正常的,非静态类,并应创建它的实例。否则,在同类产品中唯一公开显示的字段应该是常量(审议数学类,以常量如 Math.PI - 良好的使用静态方法和字段)


$ b $。 b

另外一个考虑是的凝聚力的。方法通常存在于一个类别分组,因为他们在这种或那种方式密切相关。同样,数学类是一个很好的例子;一切都在那里与数学有关。在某些时候,你会想你的全球公用事业类拆分成多个更小的,更集中的。请参见维基百科对凝聚力的一些例子,这听起来像您的使用情况下,属于巧合凝聚力(最差)


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
    }
}

解决方案

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)".

这篇关于使用静态方法和变量 - 好VS坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆