gpt4 book ai didi

design-patterns - 如何实践OOP设计的SOLID原则?

转载 作者:行者123 更新时间:2023-12-03 14:29:32 25 4
gpt4 key购买 nike

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

4年前关闭。




Improve this question




我是 SOLID 原则的新手,但我理解它。我的主要问题是很难设计我的类(class)来遵循 SOLID,特别是依赖倒置。有时将整个逻辑写入程序模式而不是使用 SOLID 很容易。

例如:

假设我们正在创建一个考勤监控系统,我们有逻辑(或程序)来扫描员工指纹,获取它的 ID,确定它是否有效,确定他在什么时间,将登录信息写入数据库,并显示它是否成功。

用一堆“if else”、循环和切换以程序方式编写它很容易。但在 future ,我将遭受“代码债务”。

如果我们在这里应用 SOLID 原则。我知道我们需要某种对象,例如“AttendanceServiceClass”,该对象具有“scanEmployeeID()”、“processthislogin()”或“isItsucessful()”等方法。而且我知道这个类依赖于存储库、用户信息和其他对象。

基本上我的问题是分析类的设计及其依赖关系

分析您的类(class)设计的逐步方法是什么?

对不起我的英语不好。

最佳答案

不是专门关于 SOLID,但值得一提的是一个非常有趣的 OOP-培训 Jeff Bay 的方法:Object Oriented Calisthenics .这个想法是,您可以尝试在非现实生活中的小型项目上遵循一套非常严格的规则。

The Rules

1. One level of indentation per method
2. Don’t use the ELSE keyword
3. Wrap all primitives and Strings
4. First class collections
5. One dot per line
6. Don’t abbreviate
7. Keep all entities small
8. No classes with more than two instance variables
9. No getters/setters/properties

By suspending disbelief, and rigidly applying these rules on a small,1000 line project, you’ll start to see a significantly differentapproach to designing software. Once you’ve written 1000 lines ofcode, the exercise is done, and you can relax and go back to usingthese 9 rules as guidelines.

This is a hard exercise, especiallybecause many of these rules are not universally applicable. The factis, sometimes classes are a little more than 50 lines. But there’sgreat value in thinking about what would have to happen to move thoseresponsibilities into real, first-class-objects of their own. It’sdeveloping this type of thinking that’s the real value of theexercise. So stretch the limits of what you imagine is possible, andsee whether you start thinking about your code in a new way.

关于design-patterns - 如何实践OOP设计的SOLID原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16638873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com