Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the SOLID principle?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is the SOLID principle". In the daily operation, I believe that many people have doubts about what is the SOLID principle. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the doubts about "what is the SOLID principle"! Next, please follow the editor to study!

01 what is the SOLID principle

The SOLID principle is actually used to guide software design. It is divided into five design principles, namely:

Single responsibility principle (SRP)

Opening and closing principle (OCP)

Richter substitution principle (LSP)

Interface isolation principle (ISP)

Dependency inversion principle (DIP)

Single responsibility principle (SRP)

The single responsibility principle (Single Responsibility Principle), which is defined as that there should be one and only one reason for a class to change. To put it simply: interface responsibilities should be single, do not take on too many responsibilities. Take the example of KFC in life: the waiter who is in charge of the cashier at the front desk should not go to the restaurant to collect dishes. The person in charge of collecting dishes in the restaurant doesn't make hamburgers.

A single responsibility applies to interfaces, classes, as well as methods. For example, we need to change the user password, there are two ways to achieve, one is to use the "modify user information interface" to change the password, and the other is to set up a new interface to change the password function. Under the guidance of the principle of single responsibility, a method has only one function, so we should set up a new interface to implement the function of changing passwords.

The focus of the principle of single responsibility lies in the division of responsibilities, which is often not immutable and needs to be determined according to the actual situation. A single responsibility can reduce class complexity, clarify responsibilities between classes, improve code readability, and make it easier to maintain. But its disadvantage is also obvious, that is, high requirements for technicians, and sometimes it is difficult to distinguish between responsibilities.

When we design a class, we can start with a coarse-grained class, and when the business develops to a certain scale, we find that there are too many coarse-grained class methods and attributes that are often modified. We can ReFactor the class and split the class into finer-grained classes, which is called continuous refactoring.

Opening and closing principle (OCP)

The opening and closing principle (Open Closed Principle), which is defined as: a software entity, such as classes, modules, and functions, should be open to extensions and closed to modifications. To put it simply: when others want to modify the software function, so that he can not modify our original code, can only add new code to achieve the purpose of software function modification.

This sounds a little mysterious. Let me give you an example.

This code simulates the process of peeling fruit. If it is an apple, it is one method of peeling; if it is a banana, it is another method of peeling. If you need to deal with other fruits in the future, you will add a lot of if else statements to it, which will eventually make the whole method smelly and long. If different varieties of this fruit happen to have different peeling methods, then there will be many layers of nesting.

If (type = = apple) {/ / deal with apple} else if (type = = banana) {/ / deal with banana} else if (type = =.) {/ / }

It can be seen that the above code does not meet the principle of "open to expansion and closed to modification". Each time you need to add a new fruit, you can modify it directly on the original code. Over time, the whole block of code becomes smelly and long.

If we do an abstraction about peeling fruit, peeling apples is a concrete implementation, and peeling bananas is a concrete implementation, then the code will look like this:

Public interface PeelOff {void peelOff ();} public class ApplePeelOff implement PeelOff {void peelOff () {/ / deal with apple}} public class BananaPeelOff implement PeelOff {void peelOff () {/ / deal with banan}} public class PeelOffFactory {private Map map = new HashMap (); private init () {/ / init all the Class that implements PeelOff interface}}. Public static void main () {String type = "apple"; PeelOff peelOff = PeelOffFactory.getPeelOff (type); / / get ApplePeelOff Class Instance. PeelOff.pealOff ();}

The above implementation makes it impossible for others to modify our code. Why?

In this way, the principle of "opening to expansion and closed to revision" has been realized.

Richter substitution principle (LSP)

The Richter substitution principle (LSP) is defined as that all references to a base class must be able to transparently use objects of its subclass. To put it simply: all the places where the parent class can appear, the subclass can appear, and the replacement will not make any errors. For example, where the Parent class appears below, you can replace it with the Son class, where Son is a subclass of Parent.

Parent obj = new Son (); equivalent to Son son = new Son ()

Such examples are very common in the Java language, but the core point is that no errors will occur if you replace them. This requires that all the same methods of the subclass must follow the conventions of the parent class, otherwise there will be an error when the parent class is replaced with the subclass. This may still be a little abstract. Let me give you an example.

In the above code, the parent class's definition of the hello method is that it can only throw a null pointer exception, but when the subclass overrides the parent class's method, it throws other exceptions, violating the parent class's convention. So when the place where the parent class appears, it is replaced by a subclass, then it is bound to go wrong.

In fact, this example is not very good, because it may have errors at the compilation level. But the meaning of the expression should be in place.

The agreement of the parent class here refers not only to the agreement on the grammatical level, but also to the agreement on implementation. Sometimes the parent class makes a description of the conventions in the class comments and method comments, and when you want to override the methods of the parent class, you need to understand these conventions, otherwise there may be problems. For example, a subclass violates the function that the parent class declares to implement. For example, a sort method of a parent class is sorted from small to big, while the method of your subclass is written to sort from big to small.

The Richter substitution principle LSP emphasizes that for users, where a parent class can be used, its subclass must be used, and the expected results are consistent.

Interface isolation principle (ISP)

The interface isolation principle (Interface Segregation Principle) is defined as that dependencies between classes should be based on the smallest interface. To put it simply: the content of the interface must be as small as possible.

For example, we often provide services to others, and there may be many service callers. In many cases, we will provide a unified interface to different callers, but sometimes caller An only uses 1, 2, 3, and other methods are not used at all. Caller B only uses methods 4 and 5, and nothing else. The principle of interface isolation means that you should extract 1, 2, 3 as an interface, and 4, 5 as an interface, so that the interfaces are isolated.

So why are you doing this? I think this is to isolate the change! Come to think of it, if we put 1, 2, 3, 4, 5 together, then when we modify the 1 method used by the A caller, although the B caller does not use the 1 method at all, but caller B is also at risk of a problem.

In addition to the change risk caused by the change, there will be other problems, such as: caller A complains why I only use 1, 2, 3 methods, and you have to write 4 or 5 methods to increase the cost of my understanding. Caller B will have the same confusion.

Dependency inversion principle (DIP)

The principle of dependency inversion (Dependence Inversion Principle) is defined as that high-level modules should not rely on underlying modules, and both should rely on their abstractions. Abstractions should not rely on details, that is, interfaces or abstract classes do not depend on implementation classes. Details should rely on abstraction, that is, implementation classes should not rely on interfaces or abstract classes. To put it simply, it means that we should program for interfaces. By abstracting it into an interface, the implementation of each class is independent of each other and the loose coupling between classes is realized.

If each of us can program through the interface, then we only need to agree on the interface definition, and we can cooperate well.

02 the essence of the SOLID principle

We finally finished talking about the five principles of the SOLID principle. But after saying this, I seem to understand, but I don't seem to remember anything. Then let's make a plate of their relationship. There was an article on ThoughtWorks that said quite well, saying:

A single responsibility is the basis of all design principles, and the opening and closing principle is the ultimate goal of design.

The Richter substitution principle emphasizes the correctness of the program when the subclass replaces the parent class, and it is used to help realize the opening and closing principle.

The interface isolation principle is used to help implement the Richter scale replacement principle, and it also embodies a single responsibility.

Dependency inversion principle is the watershed between procedural programming and object-oriented programming, and it is also used to guide the principle of interface isolation.

To put it simply: the principle of relying on inversion tells us to program for interfaces. When we program toward the interface, the principle of interface isolation and the principle of single responsibility tell us to pay attention to the division of responsibilities and not to stuff everything together.

When our responsibilities are almost the same, the Richter substitution principle tells us to pay attention to the agreement of the parent class when using inheritance. The ultimate goal of the four principles mentioned above is to realize the principle of opening and closing.

At this point, the study of "what is the SOLID principle" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report