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

标签 design-patterns dependency-injection solid-principles

关闭。这个问题需要更多 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 different approach to designing software. Once you’ve written 1000 lines of code, the exercise is done, and you can relax and go back to using these 9 rules as guidelines.

This is a hard exercise, especially because many of these rules are not universally applicable. The fact is, sometimes classes are a little more than 50 lines. But there’s great value in thinking about what would have to happen to move those responsibilities into real, first-class-objects of their own. It’s developing this type of thinking that’s the real value of the exercise. So stretch the limits of what you imagine is possible, and see whether you start thinking about your code in a new way.

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

相关文章:

c# - 是检测异常并抛出它们还是让运行时抛出它们更好?

java - 以下结构是否被视为设计模式?

java - 如何在 PageObjects 模式中使用 WebDriver/Selenium 2 LoadComponents?

java - 让 Java 代码更加通用

c# - 我怎样才能确保我正在实现开放/封闭原则?

javascript - Javascript 中这两个函数声明有什么区别?

c# - asp.net core依赖注入(inject)中注册类型时如何处理混合构造函数参数

asp.net-mvc - Ninject,如何通过调用 LoggerFactory.CreateLogger 注入(inject)通用 Logger<T>

c# - 工厂类不支持 SOLID 原则

azure - .net 7 隔离的 Azure 函数依赖注入(inject)在部署时失败(在本地工作)