方法内聚性

发布于 2024-11-04 07:49:21 字数 73 浏览 1 评论 0原文

我有保存到数据库的持久对象(插入、更新、删除)。是将该逻辑合并到一个方法中更好 - 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 技术交流群。

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

发布评论

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

评论(3

画▽骨i 2024-11-11 07:49:21

您绝对不应该将它们组合成一个方法,因为这会违反单一责任原则(我根据我自己的经验发现适用于方法设计和类设计)并且会增加 圈复杂度,从而增加测试工作量。

出于同样的原因,您可能希望有一个专门用于该目的的类,该类具有这 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.

酒废 2024-11-11 07:49:21

这确实取决于。一般来说,我会将删除分开,并且我倾向于使用单一方法进行更新/插入。

This really kind of depends. Generally speaking I would keep the delete separate, and I tend to prefer a single method for updates/inserts.

思慕 2024-11-11 07:49:21

我的偏好可能是拥有一个公共 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.

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