方法内聚性
我有保存到数据库的持久对象(插入、更新、删除)。是将该逻辑合并到一个方法中更好 - Save 还是使用 3 个单独的方法来实现内聚?
I have persistent objects that are saved to the DB (insert, update, delete). Is it better to combine this logic in a single method - Save or have 3 separate methods for cohesion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您绝对不应该将它们组合成一个方法,因为这会违反单一责任原则(我根据我自己的经验发现适用于方法设计和类设计)并且会增加 圈复杂度,从而增加测试工作量。
出于同样的原因,您可能希望有一个专门用于该目的的类,该类具有这 3 个方法。
关于内聚力,3个相关的独立方法(如您的情况)并放置在一个类中,将保持良好的内聚力,但请记住其他 类设计原则。
You should definitely not combine them into a single method because that would violate the Single Responsibility Principle (which I find from my own experience applies to method design as well as class design) and would increase cyclomatic complexity and hence, increase testing effort.
You will probably want to have a class dedicated to that purpose that has those 3 methods, for the same reason.
Regarding cohesion, 3 separate methods that are related (like in your case) and placed in a class, will keep a good cohesion, but please keep in mind the other class design principles as well.
这确实取决于。一般来说,我会将删除分开,并且我倾向于使用单一方法进行更新/插入。
This really kind of depends. Generally speaking I would keep the delete separate, and I tend to prefer a single method for updates/inserts.
我的偏好可能是拥有一个公共 Save 方法,并让该函数根据需要调用 Insert、Update 或 Delete 方法。这些方法可以是受保护的,也可以是私有的,无论什么都适合设计。
[编辑]:我应该补充一点,我可能不会将该代码放入模型类中,而是将其移动到它自己的存储库类中。我发现保持模型类非常简单可以为您的设计提供最大的灵活性。
My preference would probably be to have one public Save method and have that function call the Insert, Update, or Delete method as appropriate. Those methods can be protected or private, whatever fits the design.
[Edit]: I should add that I would probably not put that code in the model class, but move it into it's own repository class. I've found that keeping the model class very simple provides the most flexibility in your design.