您应该避免使用静态类吗? [英] Should you avoid static classes?

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

问题描述

静态类是否被视为不良做法?我几天前读了一篇关于此的文章(抱歉,找不到),它基本上说拥有静态类(尤其是那些"helper"类)通常是错误代码的标志.这是正确的吗?如果是,是出于什么原因?

are static classes considered bad practice? I read an article about this a couple days ago (can't find it, sorry) which basically said that having static classes (especially those 'helper' classes) are typically a sign of bad code. Is this correct, and if so, for what reasons?

推荐答案

滥用静态类可被视为不良做法.但是滥用任何语言功能也可以.

The abuse of static classes can be considered bad practice. But so can the abuse of any language feature.

我只区分带有静态方法的非静态类和静态类.它们实际上是同一件事,除了静态类允许编译器强制执行开发人员意图(不实例化此类,方便的语法来访问其功能,

I make no distinction between a non-static class with only static methods and a static class. They are effectively the same thing, except that static classes allow the compiler to enforce the developers intent (no instantiating this class, convenient syntax for accessing its functionality, etc).

正如您所说,"Helper"类的增多会给您带来麻烦(设计,可维护性,可读性,可发现性,其他能力...).这里没有争论.但是您可以说助手"类从不是合适的吗?我对此表示怀疑.

As you say, a proliferation of "Helper" classes can get you into trouble (design, maintainability, readability, discoverability, other-abilities...). No argument here. But can you argue that a "Helper" class is never appropriate? I doubt it.

确实,负责任地使用静态类可以为您的代码带来极大的好处:

Indeed, responsible use of static classes can have great benefits to your code:

  • Enumerable静态类提供了我们大多数人都喜欢的一组扩展方法.它们是功能/业务逻辑的逻辑集合,与任何特定类型的实例都不相关.
  • 环境/上下文提供的服务:例如,日志记录,配置(有时)
  • 其他(目前我还无法想到:))
  • The Enumerable static class provides a set of extension methods most of us have come to love. They are a logical set of functionality / business logic that isn't related a instance of any particular type.
  • Services provided by the environment/context: eg Logging, Configuration (sometimes)
  • Others (that I can't think of at the moment :))

所以不,通常来说,这是不错的做法.只要明智地使用它们...

So no, in general its not bad practice. Just use them wisely...

这篇关于您应该避免使用静态类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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