In software development, predecessors summed up some principles and patterns of software system design and development, no matter what language is used to do development, will provide guidance for our system design and development. This paper will summarize these common principles and elaborate their significance.
Development principles
There are five basic principles of object orientation (SOLID), but in addition to these five are often mentioned in addition to the Principle of Demeter and composite reuse, so in the common article there are six or seven principles. In addition to this, I will give some other principles that appear in related books and on the Internet;
S Single responsibility SRP
Single-responsibility Principle, a class should do only one thing, and only one cause it to change. The principle of single responsibility can be regarded as an extension of the object-oriented principle of low coupling and high cohesion, which defines responsibility as the cause of change in order to improve cohesion and reduce the cause of change.
define
An object should contain only a single responsibility, and that responsibility is fully encapsulated in a class. (Every object should have a single responsibility, And that responsibility should be Entirely encapsulated by the class.), that is, there is only one reason for the class change. Click here to see a detailed description of 9 options for high availability architecture design.
The principle of analysis
The more responsibilities a class (or a large module or a small method) has, the less likely it is to be reused, and if a class has too many responsibilities, they are coupled together, and when one of them changes, it can affect how the others work.
The responsibility of a class consists of two main aspects: data responsibility, which is represented by its attributes, and behavior responsibility, which is represented by its methods.
Single responsibility principle is to achieve high cohesion and low coupling guidelines, in a lot of code refactorings can be found in its existence, it is the most simple, but the most difficult to apply the principle of need to design researchers found that different duties and responsibilities of a class and its separation, and found that kind of multiple responsibilities need to design personnel has the strong ability of analysis and design and relevant reconstruction experience.
advantages
Reduce the complexity of the class and make the responsibilities of the class clear. For example, data responsibilities and behavioral responsibilities are clearly defined.
Improve readability and maintainability of classes,
The risk reduction caused by the change is essential. If the single responsibility of the interface is well done, the modification of an interface only affects the corresponding class, and has no impact on other interfaces, which is of great help to the expansibility and maintenance of the system.
Note: The single responsibility principle provides a standard for writing programs that use “responsibilities” or “reasons for change” to measure how well an interface or class is designed, but there are no specific standards for “responsibilities” or “reasons for change.” What responsibilities does a class have? How are these responsibilities detailed? Should there be an interface or class after refinement? All these need to be considered from the actual situation. It varies from project to project, from environment to environment.
O Open and closed principle OCP
Open-closed Principle,OCP, Open for extensions, Closed for modifications (core principle of design patterns)
define
A software entity (such as classes, modules, and functions) should be open for extension and closed for modification. This means that in a system or module that is open for extension and closed for modification, a good system is one that can extend your functionality without modifying the source code. The key to implementing the open close principle is abstraction.
The principle of analysis
When the software entity needs to change due to requirements, it can provide new behaviors by extending the existing software entity to meet the new requirements of the software, rather than modifying the existing code, so that the changing software has certain adaptability and flexibility. Existing software modules, especially the most important abstraction layer modules, cannot be modified, which makes the changing software system have a certain stability and continuity.
Abstract is the key to implement the open-closed principle: in the “open-closed” principle, it is not allowed to modify abstract classes or interfaces, and it is allowed to extend concrete implementation classes. Abstract classes and interfaces play an extremely important role in the “open-closed” principle. That is, to anticipate possible changes in demand. And foresee all possible known extensions.. So abstraction is key here!
The closed principle of variability: Find the variables of the system and encapsulate them. This is the best implementation of the open-closed principle. Don’t put your variables in multiple classes or scatter them all over the program. You should enclose the variable factors… And by all means do not use the variable factors of the envelope together. The best solution is to block out your variables! Avoid super-long classes, super-long classes, super-long methods! Add art to your program, the program art is our goal!
L The Richter substitution principle LSP
Liskov Substitution Principle, LSP: Wherever base classes can appear, subclasses can also appear; This idea is the constraint specification of inheritance mechanism. Only when a subclass can replace its base class, can the system recognize the subclass in the running period, which is the basis for ensuring inheritance reuse.
define
The first definition is relatively strict: if for every object o1 of type S, there is an object O2 of type T, such that the behavior of all programs P defined by T does not change when all objects O1 are substituted for O2, then type S is a subtype of type T.
The second, more understandable way of defining it is that all references to a base class (parent class) must be able to transparently use objects from its subclasses. That is, subclasses must be able to replace base classes from where they can appear. Subclasses can also add behavior to the base class.
(the Richter substitution principle was developed by BarbaraLiskov, 2008 Turing prize winner and America’s first female PhD in computer science, MIT professor, and Carnegie. Mellon University professor Jeannette Wing proposed in 1994. The text reads as follows: Let q(x) be a property provableabout objects x of type T. Then q(y) should be true for objects y of type Swhere S is a Subtype of t.)
The principle of analysis
We’re talking about the relationship between base classes and subclasses, and the Richter’s substitution rule only exists if that relationship exists. Square is rectangle is a classic example of understanding The Richter’s substitution principle.
The Richter substitution principle can be expressed colloquially as: if you can use base objects in software, you must be able to use subclass objects. If a software entity uses a subclass, it may not be able to use the base class.
Richter’s substitution principle is one of the important ways to realize the open and close principle. Because we can use the base class object everywhere, we can use the subclass object, so we try to use the base class type to define the object in the program, and then determine the subclass type at run time, and replace the parent class object with the subclass object.
I Interface isolation rule
Interface Segregation Principle (ISL) : A client should not rely on interfaces that it does not need. (This law is related to Demeter’s law.)
define
A client should not rely on interfaces that it does not need.
Another way to define it: Once an interface is too large, it needs to be broken up into smaller interfaces, and clients using the interface need only know the methods associated with it.
Note that the interface in this definition refers to the defined method. For example, a public method of a class is called outside. This method is the interface externally.
The principle of analysis
The interface isolation principle refers to the use of multiple specialized interfaces instead of a single master interface. Each interface should assume a relatively independent role, no more, no less, and do not do what should not be done, do what should be done.
An interface represents only one role, and each role has its own specific interface. This principle can be called “role isolation principle”.
Interfaces provide only the behavior that the client needs, that is, the required methods, and the behavior that the client does not need is hidden. The client should be provided with the smallest possible individual interface, rather than a large overall interface.
When splitting an interface using the interface isolation principle, a set of related operations must be defined in an interface to meet the single responsibility principle, and as few methods in the interface as possible under the premise of high cohesion.
In the system design, customized services can be used, that is, to provide different interfaces for different clients, providing only the behavior that users need, and hiding the behavior that users do not need.
D DIP
The Dependency-Inversion Principle relies on abstraction, not implementation. Specifically, high-level modules do not depend on low-level modules, but both depend on abstraction. Abstract does not depend on concrete, concrete depends on abstraction.
define
High-level modules should not depend on low-level modules; they should all depend on abstractions. Abstraction should not depend on details, details should depend on abstractions. In simple terms, the dependency inversion principle requires that clients rely on abstract coupling. Statement of Principles:
Abstraction should not depend on details; Details should depend on abstractions;
Program for the interface, not the implementation.
The principle of analysis
If open-closed principle is the goal of object-oriented design, dependent inversion principle is the means to reach the open-closed principle of object-oriented design. To achieve the best “on/off” principle, follow the dependency inversion principle as much as possible. It can be said that the principle of dependency inversion is the best specification of “abstraction”! I personally feel that the dependency inversion principle is also complementary to the Richter’s substitution principle. It should be easy to understand the dependency inversion principle after you understand the Richter substitution principle.
One of the common implementations of the dependency inversion principle is to use abstract classes in code and put concrete classes in configuration files.
Coupling between classes: zero coupling relationship, concrete coupling relationship, abstract coupling relationship. The dependency reversal principle requires that clients rely on abstract coupling, and coupling in an abstract way is the key to the dependency reversal principle.
Synthesis/polymerization reuse principle
(Composite/Aggregate ReusePrinciple, CARP) : try to use object combination instead of inheritance to achieve software reuse
define
Often referred to as the Composite ReusePrinciple or CRP, it uses a combination of objects rather than inheritance for reuse purposes.
Use existing objects in a new object and make them part of the new object. New objects reuse existing functionality by delegating to these objects. In short, use composition/aggregation as much as possible and inheritance as little as possible.
The principle of analysis
In object-oriented design, there are two basic ways to reuse existing designs and implementations in different environments: through composition/aggregation relationships or through inheritance.
Inheritance reuse: simple implementation, easy to extend. Destroy the encapsulation of the system; Implementations inherited from base classes are static, cannot be changed at run time, and do not have sufficient flexibility; Can only be used in limited environments. (” White box “reuse)
Composite/aggregate multiplexing: relatively low coupling and selective invocation of operations on member objects; It can be done dynamically at run time. (” black box “reuse)
Combination/aggregation can make the system more flexible, the degree of coupling between classes is reduced, the change of one class has less impact on other classes, so it is generally preferred to use combination/aggregation to realize reuse. Inheritance is the second consideration. When using inheritance, we should strictly follow the Richter’s substitution principle. The effective use of inheritance will help to understand the problem and reduce the complexity, while the abuse of inheritance will increase the difficulty of system construction and maintenance and the complexity of the system, so we need to carefully use inheritance reuse.
This principle is complementary to Richter’s substitution principle, both of which are specifications that implement the “open – close” principle. If we violate this principle, we cannot implement the “open-closed” principle. First, we need to understand the concepts of synthesis and aggregation:
Note: What is the difference between aggregation and composition?
Synthesis (combination) : refers to the relationship between a whole and a part, refers to a relationship that depends on the whole (the whole and the part can not be separated); For example, the eyes and mouth are combined for the head. Without the head, there are no eyes and mouth. They are inseparable. In UML, composition relationships are represented by straight lines with solid diamonds.
Demeter’s rule
(Law of Demeter, LoD: Classes in the system should try not to interact with other classes to reduce the degree of coupling between classes
define
Also known as the Least Knowledge Principle (or LKP)
Don’t talk to “strangers.” Don’t talk to strangers
Correspond only with your immediate friends. Talk only to your immediate friends.
Each software unit has minimal knowledge of other units and is limited to those closely related to its own unit.
Simply put, one object should know as little as possible about the other. A class should know the least about which classes it needs to couple or call. It doesn’t matter to me how complex you are internally. That’s your business.
Analysis of the laws of
Friend:
In Demeter’s law, there are several classes of friends for an object: (1) the current object itself (this); (2) An object passed as a parameter to the current object method; (3) Member objects of the current object; (4) If the member object of the current object is a set, then the elements in the set are also friends; (5) The object created by the current object.
Any object that meets one of the above criteria is a “friend” of the current object, otherwise it is a “stranger”.
Narrow and broad laws:
In the narrow Demeter’s law, if two classes do not have to communicate directly with each other, then the two classes should not interact directly, and if one class needs to call a method of the other class, a third party can forward the call.
In a narrow sense, Demeter’s rule:
Can reduce the coupling between classes, but will increase in the system a lot of small and scattered in every corner of the system, it can make the local design a system to simplify, because every local not is directly related and the distance of the object, but also causes system of communications between different module efficiency is lower, it is not easy to coordinate between different modules of the system. Click here to see a detailed description of 9 options for high availability architecture design.
Demeter’s law in a broad sense:
It refers to the control of information flow, direction, and influence among objects, mainly the control of information hiding. Information hiding decouples subsystems, allowing them to be developed, optimized, used, and modified independently. It also promotes software reuse, since each module exists independently of the others, so each module can be used independently of the others. The larger the system, the more important it is to hide information, and the more important it is to hide information.
The main uses of Demeter’s rule are:
It’s about controlling information overload.
In the division of classes, we should try to create loosely coupled classes, the lower the degree of coupling between classes, the more conducive to reuse, once a loosely coupled class is modified, will not cause too much impact on the associated classes;
In class structure design, each class should minimize the access permissions of its member variables and member functions;
In class design, whenever possible, a type should be designed as an immutable class;
An object’s references to other objects should be minimized to references to other classes.
Other principles of object-oriented design
Packaging changes
Use less inheritance and more composition
Programming for interfaces is not programming for implementations
Strive for loose coupling design between interacting objects
Classes should be closed to extension development and modification (open closed OCP principle)
Rely on abstractions, not concrete classes (rely on the inversion DIP principle)
The Confidant Rule: Only talk to friends (The least Knowledge rule, Demeter’s Rule)
Description: An object should know as little as possible about other objects, keep method calls within bounds, and only call methods that fall within the scope of: any object created or instantiated by this method whose component of the object itself (local method) is passed in as a method parameter
Don’t call me (call me) I’ll call you (call you) (Hollywood principle)
A class has only one reason to change it (single responsibility SRP principle)
Can you explain the Richter’s substitution principle?
Strict definition: Type S is a subtype of type T if for every object o1 of type S there is an object O2 of type T such that for all programs P defined by T the behavior of program P does not change when o1 replaces o2 for all objects.
In plain English: all references to a base class (parent class) must be able to transparently use objects from its subclasses. That is, a subclass can extend the functionality of the parent class, but cannot change the functionality of the parent class. It has the following four meanings:
A subclass can implement an abstract method of the parent class, but cannot override a nonabstract method of the parent class.
Subclasses can add their own special methods.
When a subclass’s method overrides a parent class’s method, the method’s preconditions (that is, the method’s parameters) are looser than the parent method’s input parameters.
When a subclass’s method implements an abstract method of the parent class, the method’s postcondition (that is, the method’s return value) is stricter than the parent class’s.
Under what circumstances would Demeter’s rule be violated? Why is this a problem?
Demeter’s Rule advises “only talk to friends, not strangers” to reduce coupling between classes.
Give me an example of a design pattern that meets the open and close principle?
The open closed principle requires that your code be open for extension and closed for modification. This means that if you want to add a new feature, you can easily add new code without changing the already tested code. There are several design patterns that are based on the open closed principle, such as the policy pattern. If you need a new policy, you just implement the interface, add configuration, and don’t change the core logic. One working example is the collections.sort () method, which is policy-based and follows the open and close principle. You don’t need to modify sort() for new objects. All you need to do is implement your own Comparator interface.
When to use the fly mode?
The meta pattern avoids creating too many objects by sharing objects. In order to use the share mode, you need to make sure that your objects are immutable so that you can safely share them. The String pool, the Integer pool, and the Long pool in the JDK are all good examples of using the meta schema.
Welcome to join the fan exchange group: In 705127209, Free sharing of Spring framework, Mybatis framework SpringBoot framework, SpringMVC framework, SpringCloud microservices, Dubbo framework, Redis cache, RabbitMq messages, JVM tuning, Tomcat container, MySQL database teaching video and architecture Practice mind mapping
Write at the end:
Since I see here, I feel that the author wrote a good point like, add a concern! Point attention, do not get lost, continue to update!!