名为“something-context”的类背后的想法是什么?

发布于 2024-09-12 08:38:26 字数 261 浏览 13 评论 0原文

名为 x-context 的对象(例如 Sharepoint 中的 SPContext、ASP.NET 中的 HttpContext)背后的想法是什么?我假设这些对象仅具有方法和属性来涵盖有关当前请求的所有内容(根据上面的两个示例),或者在 OrderContext 对象的情况下,包含有关与用户会话相关的订单的详细信息。

然而,这听起来就像一个名为 OrderManager 的类。

那么后缀为“Context”的类的思想是什么呢?类名什么时候应该以 Manager 结尾?

What is the thinking behind objects named x-context (e.g. SPContext in Sharepoint, HttpContext in ASP.NET)? I would assume these objects just have methods and properties to cover everything regarding the current request (as per the two examples above), or in the case of an OrderContext object, contains details about the order relating to user session.

However, this sounds just like a class called OrderManager.

So what is the thinking of a class with the suffix "Context"? And when should a class name end with the word Manager?

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

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

发布评论

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

评论(1

大姐,你呐 2024-09-19 08:38:26

HttpContext 之所以命名为 HttpContext,是因为它是当前 HTTP 请求的上下文。您在 HttpContext、SPContext 和 OrderContext 示例中给出的用于调用类 Something-Context 的基本原理对我来说似乎很正确。

假设的 HttpManager 类可以管理与 HTTP 相关的任何内容。也许它覆盖当前的 HTTP 请求,也许它充当 HTTP 客户端并发出新的 HTTP 请求,也许它设置和拆除 HTTP 服务器。这个名字真的不会告诉你。

命名一个类 ...Manager 实际上有点代码味道,原因如下:

  • 将一个类命名为通用的 ...Manager 使得将越来越多模糊相关的职责推入一个类变得太方便,违反了单一职责原则,直到成为“神级”。 (例如,参见 此处。)
  • 即使您设法避免“神级”/SRP 违规诱惑,“经理”描述性并不强
  • 良好的面向对象设计指出,您的对象可以做事情,而不是作为数据集合的对象对其进行操作。您应该拥有一个具有适当方法的 Order 类,而不是 OrderManager。您应该拥有具有适当方法的 HttpClientRequest、HttpService 和 HttpContext,而不是 HttpManager。

HttpContext is named HttpContext because it's the context of the current HTTP request. The rationale that you give in your HttpContext, SPContext, and OrderContext examples for calling classes something-context seems spot on to me.

A hypothetical HttpManager class could manage anything relating to HTTP. Maybe it covers the current HTTP request, maybe it acts as an HTTP client and makes new HTTP requests, maybe it sets up and tears down HTTP servers. The name really doesn't tell you.

Naming a class ...Manager is actually a bit of a code smell, for the following reasons:

  • Having a class named something as generic as ...Manager makes it too convenient to shove more and more vaguely related responsibilities into one class, violating the Single Responsibility Principle, until it becomes a "god class." (See, for example, here.)
  • Even if you manage to avoid the "god class" / SRP violation temptation, "Manager" isn't terribly descriptive.
  • Good OO design states that you have objects that do things, not objects-as-collections-of-data that have things done to them. Instead of an OrderManager, you should have an Order class, with appropriate methods. Instead of an HttpManager, you should have an HttpClientRequest, HttpService, and HttpContext, with appropriate methods.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文