Seven Principles of object-oriented design and seven

Source: Internet
Author: User

Seven Principles of object-oriented design and seven

Today we will talk about seven principles, namely: single responsibility, Lishi replacement, dimit law, dependency reversal, interface isolation, synthesis/aggregation principle, and openness-closure.

1. Open and Close principles(Open-Closed Principle, OCP)

Definition:The software entity shall be open to extensions and closed to modifications. This sentence is a bit professional and more popular, that is, the various components contained in the software system, such as Modules, Classes, and Functions, new functions should be extended without modifying existing code. The open and closed principle is originally "open", which means that the expansion of component functions is open and allows the extension of functions. In the principle of "open and closed ", the modification to the code is closed, that is, the original code should not be modified.

 

Problem cause: All things are generated. Let's take a look at the reason for the open and closed principles. During the software life cycle, errors may be introduced to the Old Code when the original code of the software needs to be modified due to changes, upgrades, maintenance, and other reasons, it may also cause us to have to refactor the entire function and re-test the original code. This has a significant impact on our entire system, which fully demonstrates that if the system coupling is too high, it will greatly increase the extension and maintenance in the future. To solve this problem, people have come up with the principle of opening and closing. The root solution to the open and closed principles is actually decoupling. So,Our most fundamental task in object-oriented development is decoupling..

 

Solution: When the software needs to change, try to implement changes by extending the behavior of the software entity, rather than modifying the existing code.

 

Summary: The open and closed principle is idealistic and abstract. It is the ultimate goal of object-oriented design. Several other principles can be seen as the implementation of the open and closed principles. We need to use abstraction to build a framework and implement extension details.

2.Single Responsibility Principle (Single Responsibility Principle)

Definition:A class has only one reason for its change. That is, there should be only one responsibility.

Every responsibility is a changing axis. If a class has more than one responsibility, these responsibilities are coupled. This leads to a fragile design. When a responsibility changes, other responsibilities may be affected. In addition, coupling of multiple responsibilities will affect reusability. For example, you need to separate the logic from the interface. One thing to note is that the single responsibility principle is not only exclusive to object-oriented programming ideas, but also needs to be followed by Modular programming.

 

Problem causeClass T has two different responsibilities: Class P1 and class P2. When the class T needs to be modified because of the change in the responsibility P1 requirement, it may lead to the failure of the originally running responsibility P2 function.

 

Solution: Create two classes T1 and T2 respectively, so that T1 completes the responsibility P1 function, and T2 completes the responsibility P2 function. In this way, when the class T1 is modified, the responsibility P2 will not be at risk of failure. Similarly, when the class T2 is modified, the responsibility P1 will not be at risk of failure.

3.Rys replacement principle(Liskov Substitution Principle)

 

Definition:Child type is requiredYesReplace their parent type. Note that two words can be entered here. Some people also joked that the son of a mouse would make holes.

 

Problem cause: There is A function P1, completed by Class. Now you need to extend the feature P1. The extended feature is P, where P is composed of the original feature P1 and the new feature P2. New function p is completed by subclass B of Class A. When new function P2 is completed, subclass B may fail the original function P1.

 

Solution: When Class B inherits Class A, in addition to adding A new method to complete the new function P2, try not to override the method of parent class A, and try not to reload the method of parent Class

 

Summary: All objects that reference the parent class must be transparently used. Sub-classes can expand the features of the parent class, but cannot change the original features of the parent class. That is, sub-classes can implement abstract methods of the parent class, and sub-classes can also add their own unique methods, however, it cannot overwrite non-abstract methods of the parent class. When the method of the subclass reloads the method of the parent class, the pre-condition (that is, the parameter of the method) of the method is looser than the input parameter of the parent class method. When the subclass method implements the abstract method of the parent class, the post-condition (that is, the return value of the method) of the method is stricter than that of the parent class.

4.Dimit law (Law Of Demeter)

 Definition: The dimit rule is also called the least known principle, that is, an object should have a minimum understanding of other objects. If the two classes do not need to communicate with each other directly, the two classes should not interact directly. If one class needs to call a method of another class, it can be forwarded by a third party. It is simply defined to only communicate with direct friends. First, let's explain what a friend is: Every object is coupled with other objects. As long as there is a coupling relationship between two objects, we will say that these two objects are friends. There are many coupling methods, such as dependency, association, combination, and aggregation. Here, we call the class in member variables, method parameters, and method return values as a direct friend, while the class in local variables is not a direct friend. That is to say, it is better not to appear in the class as a local variable for a strange class.

Problem cause: The closer the relationship between classes, the greater the coupling degree. When a class changes, the greater the impact on the other class.

It was first proposed by Ian Holland at Northeastern University in 1987. In general, a class knows little about its dependent classes as well. That is to say, for the dependent class, no matter how complicated the logic is, we try to encapsulate the logic inside the class as much as possible. In addition to the public method provided, we do not disclose any information externally. The dimit rule also has a simpler definition: To communicate with direct friends only.

 

Solution: Minimize coupling between classes. Since we started to engage with programming, we have learned the general principles of software programming: low coupling and high cohesion. Both process-oriented and object-oriented programming can improve the code reuse rate only when the coupling between modules is as low as possible.

 

The original intention of the dimit rule is to reduce the coupling between classes. Because each class reduces unnecessary dependencies, it can indeed reduce the coupling relationship. However, everything has a degree. Although non-direct class communication can be avoided, communication is bound to happen through an "intermediary. Therefore, excessive use of the Demeter principle will produce a large number of such intermediary and transfer classes, resulting in greater system complexity. Therefore, when using the Demeter rule, we must weigh it repeatedly to ensure a clear structure and high cohesion and low coupling.

 

5.Dependency inversion principle(Dependence Inversion Principle)

 

Definition:High-level modules should not depend on low-level modules, both of which should depend on their abstraction; abstraction should not rely on details; details should rely on abstraction. The central idea isInterface-Oriented Programming

 

Problem:Class A directly depends on Class B. To change Class A to dependent Class C, you must modify the code of Class. In this scenario, Class A is generally A high-level module responsible for complex business logic; class B and class C are low-level modules responsible for basic atomic operations; if Class A is modified, it brings unnecessary risks to the program.

 

Solution: Change Class A to dependent interface I. class B and class C implement interface I. Class A indirectly associates with Class B or Class C through interface I, this greatly reduces the chance of modifying Class.

 

In actual programming, we generally need to do the following three points:

1. The lower-layer modules should have abstract classes or interfaces, or both.

2. The variable declaration type should be an abstract class or interface.

3. Use inheritance follows the Lee's replacement principle.

 

The adoption of the dependency inversion principle has greatly facilitated collaborative development by many people. The more people participate in collaborative development and the larger the project, the more significant the adoption of the dependency-resulting principle is.

 

Summary: The principle of dependency inversion is to enable interface-oriented programming, understand interface-oriented programming, and understand Dependency inversion.

 

6.Interface isolation principle(Interface Segregation Principle)

 

Definition:The client should not rely on interfaces that it does not need; the dependency of one class on the other class should be built on the smallest interface.

 

Problem:Class A relies on Class B through interface I, and class C relies on Class D through interface I. If interface I is not the smallest interface for Class A and Class B, then class B and class D must implement the methods they do not need

 

Solution:1. Use the delegate separation interface. 2. Use multiple inheritance and separation interfaces. 3. Split bloated interface I into several independent interfaces. Class A and Class C establish dependencies with the interfaces they need. That is, the interface isolation principle is adopted.

 

Example:

Let's take a look at the figure below, and everything will be clear at a glance.

 

 

This figure indicates that Class A depends on method 1, method 2, and method 3 in interface I, and Class B is the implementation of Class A dependency. Method 1, Method 4, and Method 5 in Class C dependency interface I are the implementation of class C dependency. For class B and class D, although they all have methods that are not used (that is, the red font Mark Method in the figure), but because of the implementation of interface I, therefore, these useless methods must be implemented.

 

After modification:

 

If the interface is too bloated, as long as the methods in the interface appear, no matter whether they are useful to the classes dependent on it, these methods must be implemented in the implementation class. This is obviously not a good design. If you change this design to conform to the interface isolation principle, you must split interface I. Here we split the original interface I into three interfaces.

 

Summary: During code writing, we must use the interface isolation principle to make sure that the interface design is too large or too small. Refining the interface can improve the flexibility of the program design. However, if it is too small, it will cause too many interfaces and complicate the design. So be sure to make it moderate. When designing interfaces, you only need to spend more time thinking and planning to implement this principle accurately.

 

7. Principles of synthesis/aggregation(Composite/Aggregate Reuse Principle, CARP)

 

Definition: Some people are also called the principle of merging and reusing, andUse merging/aggregation whenever possible, and do not use class inheritance whenever possible. In other words, it is the place where synthesis/aggregation can be used without inheritance.

 

Why should we try to use synthesis/aggregation instead of class inheritance?

1. The Inheritance relationships of objects are defined at compilation, so the implementation of child classes inherited from the parent class cannot be changed at runtime.

2. The implementation of a subclass has a very close dependency with its parent class, so that any changes in the implementation of the parent class will inevitably lead to changes in the subclass.

3. when you reuse child classes, if the inherited implementation is not suitable for solving new problems, the parent class must be overwritten or replaced by other more suitable classes, this dependency limits flexibility and ultimately limits reusability.

 

Summary: these principles are fully embodied in the design patterns. The design patterns implement these principles to achieve code reuse and enhance system scalability. Therefore, many people regard the design pattern as a classic. We can study the design patterns to understand these design principles.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.