如何将单一责任原则应用于服务类别 [英] How to apply Single Responsibility Principle to a service class

查看:100
本文介绍了如何将单一责任原则应用于服务类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们正在设计一个执行CRUD(创建,读取,更新和删除)操作的UserServiceImpl类.在我看来,创建,读取,更新和删除是更改类的四个原因.该课程是否违反单一责任原则?如果违反了 那么我们应该有四个类,例如CreateUserServiceImplReadUserServiceImplUpdateUserServiceImplDeleteUserServiceImpl.拥有很多东西不是过大的杀伤力 上课?

Suppose we are designing a UserServiceImpl class which does CRUD (Create, Read, Update, and Delete) operations. In my view Create, Read, Update, and Delete are four reasons for a class to change. Does this class violates Single Responsibility Principle? If it violates, then should we have four classes like CreateUserServiceImpl, ReadUserServiceImpl, UpdateUserServiceImpl, and DeleteUserServiceImpl. Isn't it an overkill to have lots of classes?

假设我为创建,读取,更新和删除操作定义了4个接口,而我 服务类实现所有四个接口.现在我只能有一个 实现类,但是通过分离它们的接口,我将这些概念解耦为 就该应用程序的其余部分而言.这是正确的方法还是您看到一些问题 在里面吗?

Suppose I define 4 interfaces each for create, read, update, and delete operations and my service class implements all the four interfaces. Now I can only have a single implementation class but by separating their interfaces I have decoupled the concepts as far as rest of the application is concerned. Is this the right way or you see some problems in it?

推荐答案

这就是我喜欢的模式和原理-它们是每个人都可以就软件设计达成不同意见的一种统一方式:-)

That's what I love about patterns and principles - they are a consist way for everyone to disagree on software design as much as agree :-)

我的观点是,以使类成为有用且易于理解的类的任何方式来构建类-取决于类所处的复杂性和上下文.通过简单的实现和上下文,只需一个类即可.您可以说它确实遵守SRP,因为它的职责是管理CRUD操作.但是,如果实现复杂,或者有很多共享代码适合放置在抽象父类中,则可能有4个单独的类,每个CRUD操作一个都更有意义.这都是关于你如何看待它的.

My view would be to build the class in whatever way makes it a usable and easy to understand class - depending on the complexity and context within which the class lives. With a simple implementation and context, a single class will do. You could say it does adhere to the SRP because it's responsibility is to manage the CRUD operations. But if the implementation is complex, or there's a lot of shared code that would be suitable for placing in an abstract parent class, then perhaps 4 separate classes, one for each CRUD operation make more sense. it's all about how you look at it.

模式和原理是很棒的东西,但是如果使用不正确,它们可能会带来一个简单的问题,就像没有它们一样复杂.

Patterns and principles are great things, but used incorrectly they can make a simple problem just as complex as not having them.

这篇关于如何将单一责任原则应用于服务类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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