In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
1. Background
Recently, I have been reading the book "the way to structure and cleanliness". This book is really well written, and I have not updated the article recently. On the one hand, I am busy with my work, on the other hand, I am eating some books. Of course, the article still needs to be updated. I will extract some interesting content from "the way of tidy structure" and add my own thinking. The third chapter in this book introduces the design principles, which I think are more useful for everyone's daily work.
two。 Design principle
You must have learned the following principles when learning object-oriented:
SRP single responsibility: this design principle is based on the corollary of Conway's Law, and each software module has one and only one reason to be changed.
OCP opening and closing principle: open for extension and closed for modification.
LSP Richter substitution principle: wherever a base class can appear, a subclass can appear.
ISP interface isolation principle: unnecessary dependencies need to be avoided in the design.
DIP relies on the inversion principle: high-level strategic code should not rely on low-level detail code, but low-level detail code should rely on high-level policy.
These five principles are also called, and the SOLID principle takes their initials. This is also the basis for us to make a good design, which will be explained in turn.
3.SRP: single responsibility
SRP is easy to be literally unbounded, not because each module does only one thing, but because there is only one reason for each module to change. The final explanation for SRP in the book is:
Any software module should be responsible only to a certain class of actors (people with common needs).
The software module here refers to a source code file or a set of closely related functions and data structures. The SRP principle should be one of the most frequently used principles. In the book, for example, there is an Employee class that has three functions:
CalculatePay (): calculate the salary, set by the finance department, and report to CFO.
ReportHours (): calculate working hours, develop human resources, and report to COO
Save (): made by DBA and reported to CTO.
Here all three functions are placed in the Employee class, which is actually coupling the behavior of the three actors. Generally speaking, the calculation of wages will get normal working hours, and the calculation of working hours will also obtain working hours. These two functions rely on a method of obtaining working hours. If the finance department calculates wages, they want to modify the logic and see that everyone has worked hard for an hour when 1.1 hours are paid. At this time, the method of obtaining working hours is modified, but the HR department does not need this modification. This will result in a data error in the reportHours () method. So at this point, you need to split the code of different actors.
3.1 how to solve the problem
The first solution is given in the book:
Three classes are designed, each of which is related to only one actor. The downside of this problem is that the programmer needs to deal with three classes in the program, and here's how to use the facade pattern, so that we only need to use one class where we use it:
In this way, we don't need to care about the other three classes and just call the facade mode method. 3.2 actual scene
In the actual scenario, micro-service can be regarded as the idea of SRP. Although each micro-service has more than one class, the whole service can also be regarded as a module, and each module is basically related to only one actor. The method described in 3. 1 can be used in our code to implement SRP.
Benefits of SRP:
It's easy to modify the code, and it's easy because you don't need to think about whether changing the code will affect other businesses.
It is easier to maintain, and it is obviously much more difficult to maintain code with all kinds of logic than to maintain code with a single responsibility.
It is easy to find problems, and when problems arise, it is easier to locate them because of their clear responsibilities.
Loose coupling, separation of responsibilities, low degree of coupling.
4.OCP: opening and closing principle
The story of OCP in this book may be a little different from what you read from some materials. It is generally believed that the opening and closing principle should abstract those parts that are easy to change, and use multiple implementations of the abstraction to be open to extension, rather than modifying them directly in the class.
Here I use the example of eating:
Everyone eats three meals, breakfast, lunch and dinner a day, but with the progress of the times, afternoon tea, midnight snacks and so on appear, and now there are more than three meals a day. In fact, we need to add methods of drinking afternoon tea and eating midnight snacks in this category. As a result, we need to add a method without adding a type of meal. We have an example when we SRP. It is easy to modify other business logic when modifying methods in the same class, and we will also have this problem in our example. How to solve it? So we can abstract the changes: later, if you need to add eating methods, then you just need to implement this interface.
However, in this book, there is no emphasis on abstracting the part of the change, and it believes that modification is inevitable, so we need to control the impact of modification, so it is proposed that the modification of high-level components will not affect the underlying components. the lower the component level, the more stable it is. For J2EE developers, three-tier development is certainly no stranger, controller,service,dao:
If we modify controller, then service is actually imperceptible and will not be affected. If we modify service,dao, it will not be affected, but our controller will be affected. So the lower the component, the more stable it should be. In this way we can control the impact of the scope of modification. To sum up, the system is divided into a series of components, and the dependencies between these components are organized according to a hierarchical structure, so that high-level components will not be affected by the modification of low-level components.
5.LSP: Richter scale replacement
Wherever a base class can appear, a subclass must appear. Most people think that LSP is actually a way to guide how to use inheritance relationships, especially when we use spring dependency injection in the development process is basically the base class rather than the concrete implementation class, which is indeed a means of implementation of LSP. LSP is also evolving into a broader design principle that guides the interface and how it is implemented.
Here we use a negative example in the book as an example. If we are building a system that provides taxi scheduling service, we provide restful for calling. There is such a driver. If we want to schedule him, we need to access the following request:
Purplecab.com/driver/Bob/pickupAddress/24 Maple St./pickupTime/153/destination/ORD
Every company that wants to access our system has to follow the above rules, but there is a company Acme that writes destination as an acronym dest, but because this company is relatively large and does not want to change it back, the scheduling system can only write the following if logic:
If (driver.getDispatchUri () .startsWith ("acme.com")
This kind of logic ordinary software architects will not allow such a statement to appear in the system, if there is another company violation, then do you need to add another if logic? The software architect should create a scheduling request creation component and have the component use a configuration database to hold the URI assembly format, as follows:
URI scheduling format Acme.com/pickupAddress/%s/pickupTime/%s/dest/%s. *. / pickupAddress/%s/pickupTime/%s/destination/%s
But in this way, we also need to add a component to deal with this situation, which also adds complexity.
6.ISP: interface isolation principle
First of all, let's look at the following example:
Our User1,User2,User3 here depends on OPS, but User1 only needs to use op1,User2, op2,User3 and op3. In this case, although User1 does not have a direct invocation relationship with op2,op3, it also has a dependency on them at the source code level. This dependency leads to two problems:
Modifying the logic of op2,op3 will lead to changes in the logic of op1
Even if the logic does not change, modifying op2 will cause User1 to be recompiled and deployed.
We isolate different operations into interfaces by using the LSP in Section 5, we implement these three interfaces with the OPS class, and then replace the U1Ops in User1, so that the above problems do not occur because we rely on the smallest interface.
There is more emphasis on ISP in the book, and the principle of CRP is also discussed later. Don't force the users of a component to rely on things they don't need. CRP is a universal version of ISP. ISP is for classes, and CRP is for components. So we sum it up as follows:
Don't rely on things you don't need.
7.DIP: dependency inversion
Dependency inversion can be summed up as relying more on abstractions and less on concrete implementations. But everything is not so absolute, our String class is a concrete implementation class, but it can be seen everywhere in our code, does that mean we violate DIP? Actually, no, our String is already very stable, and even changes will be strictly controlled, so we don't need to worry about unexpected problems that will occur when we modify the String class. So for our stable things, in fact, the DIP principle does not apply, and what we need to focus on should be changed frequently. What I want to say here is that although people use ArrayList to write List in the coding process, they seldom write the following sentence ArrayList list = new ArrayList (), and more often write List list = new ArrayList (). In fact, this is an implementation of DIP.
Here, why is it called reversal? Where there is a reversal, there is a positive turn, as shown in the following figure:
Our serviceImpl here is the concrete implementation of service. In the figure, the flow direction of our dependencies has not changed, so it is called forward rotation. We use DIP to design:
We can see that the final flow direction here has changed, so we can ask him to rely on reversal.
DIP also has several coding rules to note:
Use more abstract interfaces and avoid using concrete implementation classes as much as possible.
Try not to create subclasses on top of concrete implementation classes.
Try not to override the methods of inherited abstract classes: since we rely on abstractions, it is possible that these methods are already dependent on logic, which can cause problems if overridden.
8. Summary
This article talked about the five principles of design SOLID,SOLID has been running through this "the way of clean architecture", these five principles can help us to make more excellent architectural design, if you want to know more details, you can read this book.
If you think this article has an article for you, you can follow my technical official account, or you can join my technical exchange group for more technical exchanges. Your follow and retweet is the biggest support for me, O (∩ _ ∩) O.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.