当尝试遵循 SOLID 原则时,我的类设计有多精细?

发布于 2024-09-19 06:08:36 字数 263 浏览 5 评论 0原文

我有一个名为 IRegistrationService 的客户端注册接口。其中包含一个名为 Register 的方法,它是通过 RegistrationService 类实现的。例如,如果我想拥有删除、更新、检索的方法,我是否会为每个操作创建一个单独的接口,例如 IDeletionService、IUpdateService、IRetrieveService,或者只是将所有方法放入 IRegistrationService 中。我之所以问这个问题,是因为这就是 SOLID 原则尤其是 SRP 原则所要求的。

I have an interface for Client Registration called IRegistrationService. This contains one method called Register and it is implemented through the class RegistrationService. If I wanted to have methods for Delete, Update, Retrieve for example, would I create a separate interface for each action such as IDeletionService, IUpdateService, IRetrieveService or just put all the methods into IRegistrationService. The reason I ask this is because this is what the SOLID principles especially the SRP principle seem to ask.

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

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

发布评论

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

评论(1

梦旅人picnic 2024-09-26 06:08:36

表述单一职责原则的一种方式是,一个类应该只有一个改变的理由。这并不一定意味着它只做一件事,而是它只处理一个责任范围。

因此,您的注册服务可以了解有关人们注册的所有信息,我会在其中包括删除、更新、检索注册。如果注册过程发生变化(例如,您决定向所有新用户或更新的用户发送电子邮件),则班级会发生变化。然而,如何发送注册电子邮件的实现细节不属于该服务——这将是该类可能更改的第二个原因(例如,您意识到您想通过外部 SMTP 服务器而不是本地发送电子邮件,或者通过短信而不是电子邮件等)。

One way of stating the Single Responsibility Principle is that a class should have only one reason to change. That doesn't necessarily mean that it only does one thing, but rather that it only deals with one sphere of responsibility.

So it's fine for your registration service to know all about people getting registered, and I'd include removing, updating, retrieving registrations in that. If the registration process changes (e.g. you decide that all new or updated users get sent an email) than the class changes. However, the implementation details of how the registration email gets sent do not belong in this service -- that would be a second reason the class might change (e.g. you realize you want to send emails via an external SMTP server rather than locally, or via SMS rather than email, etc.).

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