避免静态方法过度使用的提示 [英] Tips for avoiding Static Method Overuse

查看:54
本文介绍了避免静态方法过度使用的提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些代码,并且正在查看一个名为HFile的类. HFile具有所有私有构造函数,因此您实际上无法创建它的实例.而不是按照以下步骤创建HFile实例:

I'm refactoring some code and I'm looking at a class called HFile. HFile has all private constructors so that you can't actually create instances of it. Instead of creating instances of HFiles as follow:

var file = new HFile('filename')
file.Save()

所有HFile交互都是通过静态方法处理的.因此,如果要保存文件,我会呼叫:

all HFile interaction is handled via static methods. So if I wanted to save a file I would call:

HFile.save('filename')

,然后在内部创建一个HFile实例,然后将其保存.显然,不了解整个故事,任何读者都必须保留判断力,但是在我的工作场所,使用静态方法似乎变得非常流行.因此,我想知道是否有使用静态方法的良好原则/最佳实践,这些方法对一群坐下并回顾其静态方法使用情况的人有帮助.

and then internally an instance of HFile would be created and then saved. Obviously without knowing the whole story any reader must reserve judgment, but it seems like using static methods has become very fashionable at my place of work. So I'm wondering if there are good principles/best practices for usage of static methods that can helpful for a group of guys sitting down and reviewing their usage of static methods.

推荐答案

通常,如果您的情况需要封装状态或组织结构,则将使用类.

In general, if your situation requires encapsulation of state or an organizational structure, then you will be using classes.

另一方面,如果您有一个横切关注点,并且可以在您的应用程序中广泛使用,则可以考虑使用静态实用工具类中的方法. .NET框架(和Java)中的System.Math是此示例.

On the other hand, if you have something that is a cross-cutting concern, and can be used broadly across your application, you might consider methods in a static utility class. System.Math in the .NET framework (and Java) is an example of this.

在您的示例中,HFile可能是带有状态的对象,因此我通常不会使用静态方法来保存它.只需要对特定的HFile对象进行方法调用,而不是将整个对象传递给静态方法进行保存,就更简单了.在您的特定应用程序中是否有意义取决于您的应用程序范例将HFile对象视为要通过外部方法传递和操作的事物,还是视为能够保存自身的独立对象.

In your example, HFile is probably an object with state, so I would not generally use a static method to save it. It's simpler just to make a method call on the specific HFile object, rather than having to pass the entire object to a static method for saving. Whether that makes sense or not in your particular application depends on whether your application's paradigm sees HFile objects as things to be passed around and acted on by outside methods, or as standalone objects capable of saving themselves.

这篇关于避免静态方法过度使用的提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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