简体   繁体   English

制作方法全部静态

[英]Making Methods All Static in Class

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in the class or make the class a singleton so that you don't have to use the keyword new for calling methods in this BL class. 我的同事基于我的一个类(它是一个实例类)告诉我,如果你的类中没有字段(支持字段),只需在类中使所有方法都是静态的,或者让类成为单例,这样你就可以了不必使用关键字new来调用此BL类中的方法。

I assume this is common and good practice? 我认为这是常见且良好的做法? Basic OOP? 基本OOP? I just want to see people's opinion on that. 我只是想看看人们对此的看法。

I think basically he's saying since there's no state, no need for the methods to be instance methods. 我认为基本上他说的是因为没有状态,所以不需要将方法作为实例方法。

I'm not sure about making it a singleton every time as an option in this case...is that some sort of pattern or good advice he's giving me? 在这种情况下,我不确定每次作为一个选项让它成为一个单身......是他给我的某种模式或好建议吗?

Here's the class I'm talking about (please do not repost any of this code in this thread, this is private): http://www.elbalazo.net/post/class.txt 这是我正在讨论的类(请不要在此主题中重新发布任何代码,这是私有的): http//www.elbalazo.net/post/class.txt

There is very little downside to calling new and constructing a class reference, especially if the class has no state. 调用new和构造类引用几乎没有什么缺点,特别是如果类没有状态。 Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static. 在.NET中分配速度很快,因此我不会单独使用它作为类静态的理由。

Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class. 通常情况下,如果类没有特定的上下文,我觉得类应该是静态的 - 如果你将类作为“实用程序”方法或非上下文特定操作的占位符使用,那么成为静态类是有意义的。

If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare). 如果该类具有特定的上下文需求和具体意义,那么即使它没有状态,它也可能无法证明是静态的(尽管这种情况很少见)。 There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables. 有时候类的目的是由它的引用本身定义的,它提供了一个排序的“状态”(引用本身)而没有任何局部变量。

That being said, there is a big difference between a static class and a singleton. 话虽如此,静态类和单例之间存在很大差异。 A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created. 单例是一种不同的动物 - 当你需要一个实例时,你想要使用它,但只需要创建一个类的一个实例。 There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state. 单例中有状态,但您使用此模式强制只有一个状态副本。 This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new". 这有着非常不同的含义,我强烈建议避免使用单例来防止需要“调用新”。

There's no absolute rule for when a class should be static. 当一个类应该是静态的时候没有绝对的规则。 It may have no state, but you may need it for reference equality or locking. 它可能没有状态,但您可能需要它用于引用相等或锁定。 Classes should be static when their purpose fits it being implemented as a static class. 当类的目的适合作为静态类实现时,类应该是静态的。 You shouldn't follow hard-and-fast rules in these situations; 在这些情况下,你不应该遵循严格的规则; use what you 'feel' is right. 用你感觉'是对的。

Having no state makes it a candidate for static-ness, but look at what it's being used for before arbitarily refactoring it. 没有状态使它成为静态的候选者,但在进行仲裁重构之前,先看一下它的用途。

A lack of state alone is no reason to make methods static. 单独缺乏状态就没有理由让方法变得静止。 There are plenty of cases where a stateless class should still have instance methods. 有很多情况下无状态类仍然应该有实例方法。 For example, any time you need to pass specific implementations of some logic between routines, it's much easier to do it with classes that have instance methods, as it allows us to use interfaces: 例如,每当你需要在例程之间传递某些逻辑的特定实现时,使用具有实例方法的类就更容易,因为它允许我们使用接口:

interface IConnectionProvider
{
    object GetConnectedObject();
}

We could have a dozen implementations of the above, and pass them into routines that require an IConnectionProvider . 我们可以有上面的十几个实现,并将它们传递给需要IConnectionProvider例程。 In that case, static is a very clumsy alternative. 在这种情况下,静态是一个非常笨拙的选择。

There's nothing wrong with having to use new to use a method in a stateless class. 在无状态类中使用new来使用方法没有任何问题。

As long as you don't need to create any abstraction from your class then static methods are fine. 只要您不需要从类中创建任何抽象,那么静态方法就可以了。 If your class needs to be mocked or implement any sort of interface then you're better off making the class a singleton, since you cannot mock static methods on classes. 如果您的类需要被模拟或实现任何类型的接口,那么您最好使该类成为单例,因为您不能在类上模拟静态方法。 You can have a singleton implement an interface and can inherit instance methods from a singleton whereas you cannot inherit static methods. 您可以使用单例实现接口,并且可以从单例继承实例方法,而不能继承静态方法。

We generally use singletons instead of static methods to allow our classes to be abstracted easily. 我们通常使用单例而不是静态方法来允许我们的类很容易抽象。 This has helped in unit testing many times since we've run into scenarios where we wanted to mock something and could easily do so since the behavior was implemented as instance methods on a singleton. 这已经帮助进行了多次单元测试,因为我们遇到了我们想要模拟某些东西的场景,并且很容易这样做,因为行为是作为单例上的实例方法实现的。

Utility classes are often composed of independant methods that don't need state. 实用程序类通常由不需要状态的独立方法组成。 In that case it is good practice to make those method static. 在这种情况下,最好将这些方法设为静态。 You can as well make the class static, so it can't be instantiated. 您也可以使类静态,因此无法实例化。

With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. 使用C#3,您还可以利用扩展方法,这些扩展方法将使用这些方法扩展其他类。 Note that in that case, making the class static is required. 请注意,在这种情况下,需要使类成为静态。

public static class MathUtil
{
    public static float Clamp(this float value, float min, float max)
    {
        return Math.Min(max, Math.Max(min, value));
    }
}

Usage: 用法:

float f = ...;
f.Clamp(0,1);

I can think of lots of reasons for a non-static class with no members. 我可以想到很多没有成员的非静态类的原因。 For one, it may implement an interface and provide/augment behavior of another. 例如,它可以实现接口并提供另一个接口的/扩充行为。 For two, it may have virtual or abstract methods that allow customization. 对于二,它可能具有允许自定义的虚拟或抽象方法。 Basically using 'static' methods is procedural programming at it's worst and is contrary to object-oriented design. 基本上使用'静态'方法是程序编程最差,与面向对象设计相反。

Having said that, often small utilities routines are best done with a procedural implementation so don't shy away if it make sense. 话虽如此,通常小的实用程序例程最好用程序实现完成,所以如果有意义的话不要回避。 Consider String.IsNullOrEmpty() a great example of a procedural static routine that provides benefit in not being a method. 考虑String.IsNullOrEmpty()是程序静态例程的一个很好的例子,它提供了不作为方法的好处。 (the benefit is that it can also check to see if the string is null) (好处是它还可以检查字符串是否为null)

Another example on the other side of the fence would be a serialization routine. 围栏另一侧的另一个例子是序列化例程。 It doesn't need any members per-say. 它不需要任何成员。 Suppose it has two methods Write(Stream,Object) and object Read(Stream). 假设它有两种方法Write(Stream,Object)和对象Read(Stream)。 It's not required that this be an object and static methods could suffice; 这不是一个对象,静态方法就足够了; however, it make sense to be an object or interface. 但是,成为一个对象或接口是有意义的。 As an object I could override it's behavior, or later change it's implementation so that it cached information about the object types it serialized. 作为一个对象,我可以覆盖它的行为,或者稍后更改它的实现,以便它缓存有关它序列化的对象类型的信息。 By making it an object to begin with you do not limit yourself. 通过使它成为一个开始的对象,你不要限制自己。

Most of the time it's OK to make the class static. 大多数情况下,使类静态化是可以的。 But a better question is why do you have a class without state? 但更好的问题是为什么你没有州的课?

There are very rare instances where a stateless class is good design. 在非常少见的情况下,无状态类是良好的设计。 But stateless classes break object oriented design. 但无状态类打破了面向对象的设计。 They are usually a throwback to functional decomposition (all the rage before object oriented techniques became popular). 它们通常是功能分解的回归(面向对象技术变得流行之前的所有愤怒)。 Before you make a class static, ask yourself whether the data that it is working on should be included int he class or whether all of the functionality in the utility class shouldn't be broken up between other classes that may or may not already exist. 在使类静态化之前,请问自己,它正在处理的数据是否应该包含在类中,或者是否应该在可能存在或可能不存在的其他类之间拆分实用程序类中的所有功能。

Make sure that you have a good reason to make class static. 确保你有充分的理由让类静态化。

According to Framework Design Guidelines: 根据框架设计指南:

Static classes should be used only as supporting classes for the object-oriented core of the framework. 静态类应仅用作框架的面向对象核心的支持类。

DO NOT treat static classes as a miscellaneous bucket. 不要将静态类视为杂项桶。

There should be a clear charter for the class. 班上应该有明确的章程。

Static Class, Static Methods and Singleton class are three different concepts. 静态类,静态方法和Singleton类是三个不同的概念。 Static classes and static methods are usually used to implement strictly utility classes or making them stateless and hence thread-safe and conncurrently usable. 静态类和静态方法通常用于实现严格的实用程序类或使它们无状态,因此是线程安全的并且可以同时使用。

Static classes need not be Singletons. 静态类不必是单例。 Singleton means there is only one instance of a class, which is otherwise instantiable. Singleton意味着只有一个类的实例,否则它是可实例化的。 It is most often used to encapsulate the physical world representation of a truly single instance of a resource, such as a single database pool or a single printer. 它通常用于封装真实单个资源实例的物理世界表示,例如单个数据库池或单个打印机。

Coming back to your colleague's suggestion -- I tend to agree it is a sound advice. 回到你同事的建议 - 我倾向于同意这是一个合理的建议。 There is no need to instantiate a class if the methods are made static, when they can be static. 如果方法是静态的,当它们可以是静态的时,则不需要实例化类。 It makes the caller code more readable and the called methods more easily usable. 它使调用者代码更具可读性,并且调用的方法更容易使用。

It sounds like you're talking about a strictly Utility class, in which case there's really no reason to have seperate instances. 听起来你正在谈论一个严格的Utility类,在这种情况下,没有理由有单独的实例。

Make those utility methods static. 使这些实用程序方法静态。 You can keep the class as a regular object if you'd like (to allow for the future addition of instance methods/state information). 如果您愿意,可以将该类保留为常规对象(以允许将来添加实例方法/状态信息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使所有DAL方法静态 - Making all DAL methods static 使用所有静态方法的类有什么问题吗? - Is there anything wrong with a class with all static methods? 为什么在非静态类中有所有静态方法/变量? - Why have all static methods/variables in a non-static class? 实例化类和使用其方法并使方法静态并在不实例化类的情况下使用它们之间有什么区别 - What are the differences between instantiating a class and using its methods and making methods static and using them without instantiating the class 使 class 中的所有方法在 c# 的同一线程上运行 - Making all methods from a class to run on the same thread in c# 使Cache访问方法保持静态 - Making Cache access methods static 类与静态方法 - class vs static methods 最好将要从main()调用的所有方法声明为静态方法,还是创建一个包含所有方法(包括main)的类的对象? - Is it better to declare all methods to be called from main() as static or create an object of the class containing all the methods including main? 静态类别 具有私有构造函数的类以及所有静态属性和方法? - Static Class Vs. Class with private constructor and all static properties and methods? 使完整类变为静态并使类的功能变为静态有什么区别? - what is difference making full class static and making functions of the class as static
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM