单一职责原则 - 一个很难看到的例子?

发布于 2024-09-26 00:20:18 字数 81 浏览 1 评论 0 原文

我刚刚读到单一职责原则,Robert C. Martin 有一次指出,有时很难看出一个类具有多个职责。

谁能提供这样一个类的例子吗?

I've just read about the Single Responsibility Principle and at one point Robert C. Martin states that it is sometimes hard to see that a class has more than one responsibility.

Can anyone provide an example of such a class?

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

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

发布评论

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

评论(2

混浊又暗下来 2024-10-03 00:20:18

考虑一个具有方法

  • Get(URL url)
  • SendRequest(String request)

的 HTTP 类,这两个方法都与 HTTP 相关。但是,Get 和 SendRequest 具有不同的抽象级别。 Get实际上可能使用SendRequest来发送GET请求。因此,SendRequest 应该位于低级 HTTP 类中,而 Get 应该位于使用低级 HTTP 类的高级 HTTP 类中。

Consider a HTTP class which has methods

  • Get(URL url)
  • SendRequest(String request)

Both of these methods have to do with HTTP. However, Get and SendRequest have different levels of abstraction. Get may actually use SendRequest to send the GET request. Therefore, SendRequest should be in a low-level HTTP class, and Get should be in a high-level HTTP class which uses the low-level one.

西瓜 2024-10-03 00:20:18

这很有趣,因为另一个 StackOverflow 用户 在几个小时前在 他的问题

考虑这个类:

[Serializable]
class MyClass
{
  //Serializable fields
  public void Save()
  {
     //Saving data into file
  }

  public void Load()
  {
    //Loading data from file
  }
}

这个类(MyClass)有几个单独的角色:

  1. 这个类是可序列化的

  2. 这个类可以将他的状态保存在某个存储中

,这不是一个好主意,因为当我们打算将持久存储从简单的二进制文件更改为 Xml 文件或远程存储(例如通过 WCF)时,我们无法轻松重用此可序列化实体。

您可以创建子类,例如 MyClassWCFSaver,但即使在这种情况下,使用可序列化类 MyClass 和 MyClassSavers 的独立层次结构(具有用于 xml、二进制或 WCF 存储的多个不同子类)也更容易

,顺便说一句,这就是为什么在许多 ORM 中我们经常区分存储库中的实体(请参阅存储库模式)。

It's funny, because another StackOverflow user shows such example a couple hours ago in his question.

Consider this class:

[Serializable]
class MyClass
{
  //Serializable fields
  public void Save()
  {
     //Saving data into file
  }

  public void Load()
  {
    //Loading data from file
  }
}

This class (MyClass) has few separate roles:

  1. This class is serializable

  2. This class could save his state in some storage

In many cases this is not a good idea because we can't easily reuse this serializable entity when we deside to change our persistant storage from simple binary file to Xml file, or to remote storage (for example via WCF).

You could create subclasses, something like MyClassWCFSaver, but even in this case it much easier to use serializable class MyClass and independant hierarchy of MyClassSavers (with several different sublcasses for xml, binary or WCF storages)

BTW, thats why in many ORM we often distinquish entities from repository (see Repository Pattern).

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