我应该尽可能使我的方法静态吗?

发布于 2024-09-19 03:05:28 字数 608 浏览 3 评论 0原文

我经常思考这个问题……这可能是一个白痴问题,但就这样吧。

假设我有这个类:

public class SomeClass
{
    public int AProperty { get; set; }

    public void SomeMethod()
    {
        DoStuff(AProperty);
    }
}

这样做有什么好处吗:

public class SomeClass
{
    public int AProperty { get; set; }

    public static void SomeMethod(int arg)
    {
        DoStuff(arg);
    }
}

唯一明显的好处是我现在可以直接访问 SomeMethod

那么,在允许进行一些重构的情况下使这些方法静态化是一种很好的做法还是浪费我的时间?

编辑:我忘了提及(ShellShock 的评论提醒了我)我问的原因是我使用 ReSharper 并且它总是提出“方法 X 可以静态化”等建议......

I have often pondered this one... its probably an idiot question but here goes.

Say I have this class:

public class SomeClass
{
    public int AProperty { get; set; }

    public void SomeMethod()
    {
        DoStuff(AProperty);
    }
}

Is there any advantage to doing this:

public class SomeClass
{
    public int AProperty { get; set; }

    public static void SomeMethod(int arg)
    {
        DoStuff(arg);
    }
}

The only advantage that is obvious is that I can now access SomeMethod directly.

So is it good practice to make these kind of methods static where a little refactoring will allow or is it a waste of my time?

EDIT: I forgot to mention (and ShellShock's comment reminded me) that the reason I ask is that I use ReSharper and it always makes suggestions that 'Method X can be made static' and so on...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

桃扇骨 2024-09-26 03:05:28

静态并不是邪恶的。如果使用不当,Static 是有害的,就像我们编程工具包的许多部分一样。

Static 可能非常有利。正如此处接受的答案指出的那样, static 可能会提高速度。

作为一般规则,如果该方法不使用类的任何字段,那么这是评估其功能的好时机,但是最终可以在不实例化对象的情况下调用的实用方法通常会很有用。例如,DirectoryInformationFileInformation 类包含有用的静态方法。

编辑

我有义务指出,它确实使模拟变得更加困难,但它仍然绝对是可测试的。

这只是意味着您需要更加仔细地考虑静态方法的去向,以便您始终可以测试它们而无需依赖模拟/存根。 (即:不要将它们放在需要与数据库持久连接的 DTO 上)。

Static isn't evil. Static is evil if used incorrectly, like many parts of our programming toolkit.

Static can be very advantageous. As the accepted answer here points out, static can have a potential speed improvement.

As a general rule if the method isn't using any fields of the class then its a good time to evaluate its function, however ultimately utility methods that can be called without instantiating an object can often be useful. For instance the DirectoryInformation and FileInformation classes contain useful static methods.

Edit

Feel obligated to point out that it does make mocking a lot harder but it is still definitely testable.

It just means you need to think harder about where static methods go, so that you can always test them without needing to rely on a mock/stub. (ie: don't put them on your DTO that requires a persistent connection to the database).

幸福%小乖 2024-09-26 03:05:28

我将尝试回答涉及您提供的代码示例的具体问题。

如果 SomeMethod 仅在声明它的类中有用,我会避免静态转换并将其保留为实例方法。

如果 SomeMethod 在其所在的类之外有用,则将其从类中分解出来。这可能是某个静态实用程序类中的静态方法。为了使其可测试,请确保其所有依赖项都作为参数传递给它。如果它有大量的依赖项,您可能需要检查设计并准确地弄清楚它应该做什么 - 作为您传递给它的类之一的实例方法可能会更好。

有人说静电是邪恶的。这通常是因为可变静态提供的陷阱,其中变量从静态构造函数被调用到应用程序域的拆除一直存在,并在其间发生变化。依赖于该状态的代码可能会出现不可预测的行为,并且测试可能会变得非常可怕。但是,不引用可变静态的静态方法绝对没有问题。

对于一个(非常简单的)示例,其中静态是邪恶的,但可以转换为非邪恶版本,想象一个计算某人年龄的函数:

static TimeSpan CalcAge(DateTime dob) { return DateTime.Now - dob; }

可以测试吗?答案是否定的。它依赖于非常不稳定的静态状态,即 DateTime.Now。不能保证每次相同的输入都会有相同的输出。为了使其更易于测试:

static TimeSpan CalcAge(DateTime dob, DateTime now) { return now - dob; }

现在函数依赖的所有值都被传入,并且它是完全可测试的。相同的输入将得到相同的输出。

I'll attempt to answer your specific question involving the code sample you provided.

If SomeMethod is only useful in the class it is declared in, I would avoid the static conversion and leave it as an instance method.

If SomeMethod is useful outside of the class it is in, then factor it out of the class. This may be as a static method in a static utility class somewhere. To make it testable, ensure that all its dependencies are passed in to it as arguments. If it has loads of dependencies, you might want to review the design and figure out exactly what it's supposed to be doing - it might be better as an instance method in one of the classes you're passing in to it.

Some people say that static is evil. This is generally because of the pitfalls that mutable static state provides, where variables hang around from the point a static constructor is called to the tear down of an app domain, changing in between. Code reliant on that state can behave unpredictably and testing can become horrendous. However, there is absolutely nothing wrong with a static method which does not reference mutable static state.

For a (very simple) example where a static is evil, but can be converted to a non-evil version, imagine a function that calculates someone's age:

static TimeSpan CalcAge(DateTime dob) { return DateTime.Now - dob; }

Is that testable? The answer is no. It relies on the massively volatile static state that is DateTime.Now. You're not guaranteed the same output for the same input every time. To make it more test friendly:

static TimeSpan CalcAge(DateTime dob, DateTime now) { return now - dob; }

Now all the values the function relies on are passed in, and it's fully testable. The same input will get you the same output.

晚雾 2024-09-26 03:05:28

静态方法是有意义的,如果您应该能够在之前不创建类的对象的情况下调用它们。例如,在 Java 中,Math 类仅包含静态方法,因为实例化 Math 类仅用于对其他对象执行数学运算没有多大意义。

大多数时候最好避免使用静态方法。您应该熟悉面向对象编程 - 有很多好的资源,解释了静态方法等所有概念。

Static methods make sense, if you should be able to call them without creating an object of the class before. In Java, for example, the Math-Class contains only static methods, because it wouldn't make much sense to instanciate a Math-Class only to do mathematical operations on other objects.

Most of the time it's better to avoid static methods. You should get familiar with object oriented programming - there are lots of good resources out there, explaining all the concepts like static methods, etc.

夜巴黎 2024-09-26 03:05:28

我认为这取决于您想要使用这些方法的方式。如果静态方法用作类的几个实例的通用方法,那么使用静态方法是可以的。

举个例子,假设您有一个字符串类和两个字符串 A 和 B。要比较 A 和 B,您可以使用 A.CompareTo(B) 方法或 String.Compare(A, B) 方法。

如果我错了,请纠正我。

I think it will depend on the way you want to use the methods. Using a static method is okay if it is used as a common method over a few instances of the class.

For the sake of an example, say you have a string class and two strings A and B. To compare A and B, you can either have a A.CompareTo(B) method or String.Compare(A, B) method.

Please correct me if I am wrong.

指尖凝香 2024-09-26 03:05:28

不。静态是邪恶的。它将调用者与所使用的类紧密耦合在一起 使得测试变得困难

No. Static is evil. It tightly couples the caller to the used class and makes it hard to test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文