实用类..好还是坏? [英] Utility classes.. Good or Bad?

查看:155
本文介绍了实用类..好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在读,通过在代码中使用静态类/单例创建依赖,是坏的形式,并创建问题ie。紧耦合和单元测试。

I have been reading that creating dependencies by using static classes/singletons in code, is bad form, and creates problems ie. tight coupling, and unit testing.

我有一种情况,我有一组url解析方法没有与其关联的状态,并只使用输入方法的参数。我相信你熟悉这种方法。

I have a situation where I have a group of url parsing methods that have no state associated with them, and perform operations using only the input arguments of the method. I am sure you are familiar with this kind of method.

过去,我将继续创建一个类并添加这些方法,并直接从我的代码中调用它们,例如

In the past I would have proceeded to create a class and add these methods and call them directly from my code eg.

UrlParser.ParseUrl(url);

但等一下,就是引入一个依赖到另一个类。我不确定这些效用类是否是坏的,因为它们是无状态的,这最小化了所述静态类和单例的一些问题。有人可以澄清这一点吗?

But wait a minute, that is introducing a dependency to another class. I am unsure whether these 'utility' classes are bad, as they are stateless and this minimises some of the problems with said static classes, and singletons. Could someone clarify this?

我应该把方法移动到调用类,也就是说,如果只有调用类将使用该方法。这可能违反了单一责任原则。

Should I be moving the methods to the calling class, that is if only the calling class will be using the method. THis may violate the 'Single Responsibilty Principle'.

推荐答案

从理论设计的角度来看,我觉得Utility类尽可能避免。它们基本上没有什么不同于静态类(虽然略微更好,因为他们没有状态)。

From a theoretical design standpoint, I feel that Utility classes are something to be avoided when possible. They basically are no different than static classes (although slightly nicer, since they have no state).

然而,从实践的角度来看,我创造这些,请在适当时使用 。尝试避免实用程序类通常很麻烦,并且导致更少的可维护代码。但是,我尽量鼓励我的开发者在可能的时候避免使用公共API。

From a practical standpoint, however, I do create these, and encourage their use when appropriate. Trying to avoid utility classes is often cumbersome, and leads to less maintainable code. However, I do try to encourage my developers to avoid these in public APIs when possible.

例如,在你的情况下,我觉得UrlParser.ParseUrl )可能更好地处理一个类。查看BCL中的 System.Uri - 这将处理干净,易于使用的统一资源标识符接口,工作良好,并保持实际状态。我喜欢这种方法,一个工作在字符串的实用程序方法,并强制用户传递一个字符串,记得验证它等。

For example, in your case, I feel that UrlParser.ParseUrl(...) is probably better handled as a class. Look at System.Uri in the BCL - this handles a clean, easy to use interface for Uniform Resource Indentifiers, that works well, and maintains the actual state. I prefer this approach to a utility method that works on strings, and forcing the user to pass around a string, remember to validate it, etc.

这篇关于实用类..好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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