OO (Object-Oriented) Design Principles

Source: Internet
Author: User
Document directory
  • Basic Principles
  • SRP: The single responsibility principle single responsibility
  • DRY: Don't repeat yourself Principle
  • OCP: Open-Close Principle
  • LSP: The Liskov substitution principle
  • DIP: Dependency inversion principle
  • ISP: interface isolation principle

1. SRP-single Responsibility Principle

2. OCP-open and closed Principle

3. LSP ---- Liskov replacement principle

4. DIP ---- Dependency inversion principle

5. ISP-interface separation principle

Agile development advocates the practice of simple design, and "seize the opportunity to improve design when new requirements are met" is closed for changes of similar nature, design evolution driven by changes in demand (we cannot blame changes in demand for design degradation), and experience plays a very important role here, if Experienced designers can make necessary abstractions to satisfy the ocp principles during the initial design based on experience, or determine the abstraction required by the system (required closed) when the demand changes ), of course, this change should be stimulated early (such as test-driven development methods ).

OOD promises a series of benefits (flexibility and reusability and maintainability). It is designed and developed in OO language. To achieve these benefits conveniently, there are a series of principles to follow, such as SRP, OCP, LSP, ISP, etc.

SRP (single responsibility principle) maintains the simplicity of the class. The class should not take on more than one reason for its changes. Otherwise, the class should be separated and re-constructed, however, if the change of the application always leads to the simultaneous change of duties in the class, there is no need to separate them.

Ocp (open and closed principle) enables the OO system to be open to expansion and closed to modification. The key to OCP's compliance lies in abstraction. Its main implementation methods include: defining interfaces to describe the required operations. The client only needs to focus on interface calls, and the child type can implement interfaces in any way it chooses, namely, the so-called stategy mode, or the definition of an abstract class and implement public operations in it. The personalized operations are defined as abstract or virtual, and the child type is responsible for personalized implementation. Through these two methods, separate the general parts and implementation details of the function. Of course, the designer should determine (by speculation or by experience) which changes the system is closed to, because it is impossible to close all changes, as mentioned in agile mode practice, in order to close the sorting arrangement (or change) (so that the subtypes do not need to know each other, you can also arrange the sorting order freely), and select the "data-driven" method (that is, separately constructing a structure to represent the sorting arrangement-where the sub-class type is arranged in the structure in order of the table ), you can implement one Precedes operation in the shape base class without implementing the Child types separately. As the core of OOD, OCP relies on abstraction. However, agile design (or good design) rejects immature abstraction, and programs only need to abstract frequently changed parts.

The Liskov replacement principle makes ocp one of the possible principles. It emphasizes that "subtypes must be able to replace their base types basetype" and control the inheritance relationship arrangement of OO, in OOD, is-a is used to determine the inheritance relationship between classes. LSP points out that this is-a relationship is in terms of behavior methods (that is, operations of classes, the behavior method can be reasonably assumed and is dependent on the customer program. To comply with the LSP, you can use the design by contract operation preconditions and preconditions. "to perform an operation, the preconditions must be true. After the operation is completed, this operation must ensure that the post condition is true (it is helpful to indicate the pre-and post-conditions for each method). In this way, "when you re-declare an operation in a derived class, only equal or weaker preconditions can be used to replace the original preconditions, only equal or stronger post conditions can be used to replace the original post conditions. (The abstract methods between interfaces and their implementations must meet the preceding conditions ). At the same time, the above ocp can follow the two modes used to make the design conform to the LSP. In addition, the exception throw in the Child type should be considered within the range that follows the LSP.

Design Tools for extracting the public part: "extract the public responsibility and put it into the super class. The new child types added later may support the same responsibilities in a new way, in this case, the original superclass may be an abstract class ".

DIP (dependency inversion principle) is the core of framework Design. Compared with traditional software design, DIP uses structural design to directly call underlying modules with high-level modules, in this way, the high-level module will depend heavily on the changes of the underlying module. In OOD, by defining the required service interfaces for the high-level module, the underlying module actually has such interfaces, the high-level module uses the next layer (declared by the strategy Mode) through the abstract interface. In this case, the interface owner is generally its user rather than its real-time user. Generally, in order to meet DIP-good basic underlying mechanism of Good OOD, I need to find potential abstractions in the system, which are usually those that do not change with specific details.

ISP interface isolation principles, such as the simplicity of the SRP maintenance class, the simplicity and necessity of the ISP to maintain the interface, because the interface is called by the customer, therefore, it should be "suitable size". The "fat" interface is obviously cumbersome for callers, and the ISP is used to separate the "fat" interface into multiple suitable interfaces.

Of course, it is not easy to achieve this in system design and implementation. Simply knowing its existence may not necessarily be realized into the system, the accumulation of development experience is equally important, but I knew there was a consciousness earlier and took it into consideration when I was doing it. It was also accumulation. Come on, n more things to do.

-- Agile Software Development: Principles and Practices

===================================== Another version

What are design principles?

Design principles are basic tools. applying these rules can make your code more flexible, easier to maintain, and easier to expand.

Basic Principles

  • Encapsulation change Encapsulate what varies.
  • It is intended for interface programming rather than implementing Code to an interface rather than to an implementation.
  • Combination is preferred, rather than Favor Composition Over Inheritance
SRP: The single responsibility principle single responsibility

Each object in the system should have only one separate responsibility, and all objects focus on the completion of their own responsibilities.

Every object in your system shocould have a single responsibility, and all the object s services shocould be focused on carrying out that single responsibility.

  1. Each responsibility is a design change. When the demand changes, the demand changes are reflected in the changes of class responsibilities. When the objects in your system have only one reason for change, you have followed the SRP principle.
  2. If a class has too many responsibilities, these responsibilities are coupled. A change in responsibility may weaken or suppress the ability of other responsibilities of this category. This design will lead to a fragile design. When a change occurs, the design will be unexpectedly damaged.
  3. SRP makes the system easier to manage and maintain because not all problems are involved.
  4. Cohesion is actually another name of the SRP principle. If you write high Cohesion software, it means that you have applied the SRP principle well.
  5. How can we determine whether a responsibility is an object? You try to let this object fulfill this responsibility by yourself. For example, "the book reads the content by yourself" is clearly not the responsibility of the book.
  6. Only when a change occurs can the changed axis have practical significance. If there is no indication, it is unwise to apply SRP or any other principles.
DRY: Don't repeat yourself Principle

Avoid code duplication by extracting public parts and placing them in one place.

Avoid duplicate code by Using acting out things that are common and placing those thing in a single location.

  1. DRY is simple, but it is the key to ensuring that our code is easy to maintain and reuse.
  2. What do you actually do when you try to avoid repeated code? It is to ensure that every requirement and function is only implemented once in your system, otherwise there will be a waste! There is no intersection between system use cases, so our code should not be repeated. From this perspective, DRY is not just about code.
  3. DRY focuses on information and behavior in the system in a single, obvious position. Just like you can guess the position of a regular expression in. net, you can guess it because it is reasonable.
  4. DRY principle: how to effectively split system functions! The clear division of duties ensures the uniformity of code to a certain extent.
OCP: Open-Close Principle

Class should be closed for modification and open for extension;

Classes shoshould be open for extension, and closed for modification.

  1. OCP focuses on flexibility. changes are made by adding code, rather than modifying existing code;
  2. OCP applications are limited to changes that may occur. Similar changes that may occur in the future are isolated by creating abstractions.
  3. The OCP principle conveys the idea that once you write code that can work, you must strive to ensure that this code can always work. This is a bottom line. A little higher requirement, once our code quality reaches a level, we need to do our best to ensure that the code quality does not roll back. Such requirements prevent us from solving a problem by means of a live solution, or by letting ourselves flow; for example, the Code has added numerous processes for specific data, and more special code is available. The Code intent is ambiguous and degrades.
  4. The mechanism behind OCP: encapsulation and abstraction. Blocking is based on abstraction, and display is obtained using abstraction. inheritance is the simplest example of OCP. In addition to subclass and method overloading, we also have some more elegant methods for implementation, such as combination;

How can I change the source code without changing the source code (disabling modification? The answer is abstraction. The mechanism behind OCP is abstraction and polymorphism.

  1. There is no appropriate model that can adapt to all situations! There must be changes and it is impossible to completely close them. It is not a good idea to abstract every part of the program. The correct approach is that developers only abstract the frequently changed part. Rejecting immature abstractions is just as important as abstraction itself.
  2. OCP is the core of many claims by OOD. If this principle is applied effectively, we can gain stronger maintainability, reusable flexibility, and robustness. LSP is one of the main principles that OCP has become possible.
LSP: The Liskov substitution principle

The subclass must be able to replace the base class.

Subtypes must be substitutable for their base types.

  1. LSP focuses on how to use inheritance well.
  2. You must know whether to use a Method or extend it, but it is definitely not changed.
  3. LSP clearly pointed out that the IS-A relationship of OOD is in terms of the behavior mode, the behavior mode can be reasonable assumptions, is the customer program relies on.
  4. LSP makes us come to an important conclusion: If a model is isolated, it is not really effective. The validity of the model can only be expressed through its customer program. It must be examined based on reasonable assumptions made by the intended user. The assumption is unpredictable and will not be handled until the design odor appears.
  5. LSP violations may also violate OCP
DIP: Dependency inversion principle

The high-level module should not depend on the underlying module, both of which should depend on abstraction.

Abstraction should not depend on details. Details should depend on abstraction.

  1. What is a high-level module? The high-level module includes important policy selection and business model in applications. These high-level modules differentiate their applications from others.
  2. If the high-level module depends on the underlying module, it is very difficult to reuse the high-level module in different contexts. However, if the high-level module is independent of the underlying module, the high-level module can be easily reused. This principle is the core principle of the Framework Design.
  3. The inversion here is not only the inversion of dependency, but also the inversion of interface ownership. When DIP is applied, we will find that customers often have abstract interfaces, and service providers derive from these abstract interfaces.
  4. This is the famous principle of Hollywood: "Don't call us we all call you." The underlying module implements the interface declared in the high-level module and called by the high-level module.
  5. By putting the image upside down, we created a more flexible, persistent, and easy-to-change structure.
  6. The simple heuristic rule of DIP: dependent on abstraction; this is a simple statement. The suggestion of this rule should not depend on a specific class, that is to say, the program summarizes all dependencies and should be planted in abstract classes or interfaces.
  7. If a class is stable, it does not cause any harm. However, most of our own classes are unstable. By hiding them behind abstract interfaces, they can isolate instability.
  8. Dependency inversion can be applied to any place where one class sends messages to another class.
  9. The dependency inversion principle is the basic underlying mechanism to realize the benefits of many Object-oriented technologies, and is the symbol of object-oriented.
ISP: interface isolation principle

Customer programs should not be forced to rely on methods they do not need.

  1. The interface is not highly cohesive. An interface can be divided into N groups of methods, so this interface needs to be processed by ISP.
  2. The division of interfaces is determined by the customer program that uses it. The customer program is a separate interface and should also be separated.
  3. When an interface contains too many behaviors, leading to abnormal dependencies between their customer programs, what we need to do is to separate the interfaces and implement decoupling.
  4. After applying the ISP, the customer program will see multiple cohesive interfaces.

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.