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

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

问题描述

我一直在读,通过在代码中使用静态类/单身创建依赖关系,是坏的形式,并创建问题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'.

推荐答案

从理论设计的角度来看,我觉得实用工具类的东西是时避免可能的。他们基本上都不会比静态类不同的(虽然略显更好,因为他们没有状态)。

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(... )可能是更好的为一类处理。看看的System.Uri 在BCL - 这种处理干净,易于使用的界面,统一资源Indentifiers,行之有效,并保持实际状态。我喜欢这种方法,一个是对字符串工程实用方法,并强迫用户绕过一个字符串,记得要验证它,等等。

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天全站免登陆