7 Object-Oriented design principles

Source: Internet
Author: User

Object-Oriented design principles

I. Overview

For maintainability and reusability of software, the well-known software guru Robert C.martin believes that a low-maintainability (maintainability) software design is usually caused by 4 reasons: too stiff (rigidity), too fragile (fragility ), low multiplexing rate (immobility), high viscosity (Viscosity). The software engineering and modeling guru Peter Coad believes that a good system design should have the following three properties: Extensibility (Extensibility), flexibility (flexibility), pluggable (pluggability).
Software reuse (reuse) or reuse has many advantages, such as improving software development efficiency, improving software quality, saving development costs, and the appropriate reuse can also improve the maintainability of the system. The goal of object-oriented design multiplexing is to enable multiplexing that supports maintainability. In object-oriented design, maintainability reuse is based on the principle of object-oriented design, which is the principle of reuse, which can effectively improve the reusability of the system and improve the maintainability of the system. The object-oriented design principle and design pattern are also the compass to reconstruct the system rationally, and the reconstruction (refactoring) is to improve the quality and performance of the software by adjusting the program code without changing the existing functions of the software, and make the design pattern and structure of the program more reasonable, and improve the expansibility and maintainability of the software.
Commonly used object-oriented design principles include 7, these principles are not isolated, they depend on each other and complement each other.


Two or seven main principles details

(i) Single principle of responsibility (Responsibility Principle, SRP)

1, definition: An object should contain only a single responsibility, and the responsibility is completely encapsulated in a class. (Every object should has a single responsibility, and that responsibility should is entirely encapsulated by the class.)
Or: In the case of a class, there should be only one cause for it to change. (There should never is more than one reason for a class-to-change.)
2, Analysis: A class (or large to the module, small to the method) the more responsibility, it is more likely to be reused, and if a class assumed too much responsibility, it is equivalent to the responsibility of coupling together, when one of the responsibilities changes, may affect the operation of other functions.
The responsibilities of the class include two aspects: data responsibility and behavior responsibility, data responsibility is embodied by its attribute, and behavior responsibility is embodied by its method.
Single responsibility principle is to achieve high cohesion, low-coupling guidelines, in many code refactoring techniques can find its existence, it is the simplest but the most difficult to apply the principle, requires designers to discover the different responsibilities of the class and separate it, and the discovery of multiple responsibilities of the class requires designers have strong analytical design capabilities and related refactoring experience.
3. Example:

Example description
A Java-based C/s system "login function" is implemented by the following login class (login):






A single responsibility principle is now used to reconstruct it.


(ii) Opening and closing principle (open-closed Principle, OCP)

     1, definition: A software entity should be open to extensions and closed for modifications. In other words, when designing a module, it should be allowed to be extended without modification, that is, to change the behavior of the module without modifying the source code. (software entities should is open for extension and closed for modification.)
     2, Analysis: Open and closed Principle by Bert Rand Meyer, introduced in 1988, is one of the most important principles in object-oriented design. In the definition of open and closed principle, a software entity can refer to a software module, a local structure consisting of multiple classes, or a separate class. Abstraction is the key to the open and closed principle. The
open and close principle can also be described by a more specific "principle of variability encapsulation", which requires that the variable packaging principle (Principle of encapsulation of variation, EVP) be found and encapsulated in the system.
     3, Example:

(iii) The principle of substitution of the Richter scale (Liskov Substitution Principle, LSP)
      1, definition: If you are O1 for each object of type S, There are object O2 of type T, so that all program P defined in T is replaced with O2 for all objects O1, so the behavior of P is not changed, then the type S is a subtype of type T. (If for each object O1 of type S There are an object O2 of type T such so for all programs P defined in terms of T, the B Ehavior of P is unchanged when O1 are substituted for O2 then S is a subtype of T.) or: All references to base classes (parent classes) must be able to transparently use objects of their subclasses. (Functions that use pointers or references to base classes must is able to use objects of derived classes without knowing it.)
     2, Analysis: the principle of substitution of the Richter scale by 2008 Turing Award winner, the first U.S. computer Science woman PhD, MIT professor Barbara Liskov and Carnegie Mellon University Jeannette Professor Wing was introduced in 1994. The original text is as follows: Let Q (x) is a property provable about objects X of type T. then Q (Y) should was true for objects Y of the type S where S is a subtype of t.   

The

     Richter substitution principle can be expressed in layman's terms: If you can use a base class object in the software, you must be able to use its subclass object. Replace the base class with its subclasses, the program will not produce any errors and exceptions, and conversely, if a software entity uses a subclass, then it is not necessarily able to use the base class. The principle of substitution of the Richter scale is one of the important ways to realize the open and closed principle, because the subclass object can be used wherever the base class object is used, so as far as possible the base class type is used in the program to define the object, while at run time the subclass type is determined, and the child class object is substituted for the parent class object.
     3, Example:


(iv) reliance on reversal principle (dependence inversion Principle, DIP)
1, definition: High-level modules should not rely on low-layer modules, they should be dependent on abstraction. Abstractions should not be dependent on detail, and detail should be dependent on abstraction. (modules should not depend upon low level modules, both should depend upon abstractions. Abstractions should not depend upon details, details should depend upon abstractions.) or: To program for the interface, do not program for implementation. (Program to a interface, not a implementation.)
2, Analysis: The principle of dependence reversal is Robert C. Martin in 1996 for the "C + + Reporter" column Engineering notebook third, and later added to his 2002 edition of the classic "Agile software Development, principles, Patterns, and practices.
Simply put, the dependency reversal principle means that the code relies on abstract classes rather than on specific classes, programming to interfaces or abstract classes, rather than specific classes.
The key to realize the open and close principle is abstraction, and from abstract to materialize realization, if the principle of opening up is object-oriented design, then the dependency reversal principle is the main means of object-oriented design.

One of the common implementations of the dependency reversal principle is to use abstract classes in your code and place specific classes in the configuration file.

Coupling between classes
0 coupling relationship
Specific coupling relationship
Abstract coupling relationship
The dependency reversal principle requires the client to rely on abstract coupling, and abstract coupling is the key to the dependency reversal principle.


Dependency Injection
Construct injection (Constructor injection): Injects an instance variable through a constructor.
Set value injection (setter injection): injects instance variables through setter methods.
Interface Injection (Interface injection): Injects an instance variable through an interface method.

3. Example:

(v) Interface Isolation principle (Interface segregation Principle, ISP)

1, definition: The client should not rely on those interfaces it does not need. (clients should not being forced to depend upon interfaces.) [Note that the interface in this definition refers to the method that is defined.] ] OR: Once an interface is too large, it needs to be split into smaller interfaces, and clients using that interface need only know the methods associated with them. (Once an interface have gotten too ' fat ' it needs to is split into smaller and more specific interfaces so, any clients Of the interface would only know about the methods, that pertain to them. )
2, Analysis: the principle of interface isolation refers to the use of multiple specialized interfaces, without using a single total interface. Each interface should assume a relatively independent role, not a lot, do not do the things that should be done to do.
(1) An interface represents only one role, and each role has its own specific interface, and this principle can be called the "role isolation principle".
(2) The interface only provides the behavior that the client needs, that is, the required method, the client does not need to hide the behavior, should provide the client with the smallest possible separate interface, rather than provide a large total interface.

When you split an interface using the interface isolation principle, you must first meet a single principle of responsibility, define a set of related operations in an interface, and, with high cohesion, the fewer methods in the interface are as good as possible.
Can be used in the design of the system in a customized way, that is, for different clients to provide a wide range of interfaces, only the user needs to provide the behavior, and hide the user does not need the behavior.

3. Example:

(vi) Synthetic multiplexing principles (Composite reuse Principle, CRP), also known as combinatorial/aggregation multiplexing principles (composition/aggregate reuse Principle, CARP)

1, definition: Try to use the object combination, rather than inheritance to achieve the purpose of reuse. (Favor composition of objects over inheritance as a reuse mechanism.)

2. Analysis: The principle of synthetic reuse refers to the use of some existing objects in a new object through association relationships (including combinatorial relationships and aggregation relationships) to make them part of new objects; The new object is used to re-use its existing functions by delegating methods that call existing objects. In short: Use the combination/aggregation relationship as much as possible, with less inheritance.
In object-oriented design, there are two basic methods for reusing existing designs and implementations in different environments, that is, by combining/aggregating relationships or through inheritance.
Inheritance reuse: Simple to implement and easy to scale. The encapsulation of the system is compromised; the implementations inherited from the base class are static, impossible to change at run time, not flexible enough, and can only be used in a limited environment. ("White box" multiplexing)


Combination/Aggregation multiplexing: a relatively low degree of coupling, optionally invoking the operation of a member object, which can be performed dynamically at run time. ("black box" multiplexing)
Combination/aggregation can make the system more flexible, the coupling between classes and classes is reduced, the change of one class has a relatively small impact on other classes, so it is generally preferred to use combination/aggregation to achieve reuse, followed by inheritance, in the use of inheritance, need to strictly follow the Richter substitution principle, effective use of inheritance will help to understand the problem , reducing complexity, while abusing inheritance increases the difficulty of building and maintaining the system and the complexity of the system, so you need to use inheritance reuse sparingly.
3. Example:

(vii) Dimitri (Law of Demeter, LoD) also known as the least-knowledge principle (Least knowledge Principle, LKP)

1. Definition:

(1) Do not talk to "strangers". The English definition is: Don ' t talk to strangers.
(2) communicate only with your direct friends. The English definition is: talk only to your immediate friends.
(3) Each software unit has only the least knowledge of the other units, and is limited to the software units closely related to the unit.     The English definition is as follows: Each unit should has only limited knowledge on other units:only units "closely" related to the current unit. 2, Analysis: Dimitri Law from the 1987 fall of the United States Northeastern University (Northeastern University) a research project called "Demeter". To put it simply, the Dimitri rule means that a software entity should interact with as few entities as possible. Thus, when a module is modified, it will minimize the impact of the other modules, the extension will be relatively easy, this is the software entity communication between the restrictions, it requires limiting the width and depth of communication between software entities.

In the Dimitri law, for an object, its friends include the following categories:
(1) The current object itself (this);
(2) An object that is passed into the current object method in the form of a parameter;
(3) The member object of the current object;
(4) If the member object of the current object is a collection, then the elements in the collection are also friends;
(5) The object created by the current object.
Any object, if one of the above conditions is met, is the "friend" of the current object, or "stranger".

Dimitri Law can be divided into narrow law and generalized law. In the narrow Dimitri law, if two classes do not have to communicate with each other directly, then these two classes should not have direct interaction, if one of the classes needs to invoke a method of another class, you can forward the call through a third party.

Narrow-Dimitri law: can reduce the coupling between classes, but will add a large number of small methods in the system and scattered in the system, it can make a system of local design simplification, because each part will not and long-distance objects have a direct association, but also will cause the system of different modules communication efficiency is reduced, Makes the system not easy to coordinate between the different modules.
Generalized Dimitri Law: refers to the control of information flow, flow direction and the influence of information, mainly on the control of information hiding. The concealment of information can decouple the subsystems, allowing them to be developed, optimized, used and modified independently, while facilitating the reuse of the software, since each module does not depend on other modules, so each module can be used independently of other places. The larger the size of a system, the more important it is to conceal information, and the greater the importance of information hiding.


The main purpose of the Dimitri Law is to control the overload of information:
In the division of classes, we should try to create loosely-coupled classes, the lower the coupling between classes, the more conducive to reuse, a loosely coupled class once modified, will not cause too much impact on the associated classes;
In the structure design of the class, each class should minimize its member variables and the access rights of member functions;
In the design of a class, whenever possible, a type should be designed as an immutable class;
On references to other classes, one object's references to other objects should be minimized.


3. Example:

Summary of three or seven object-oriented design principles

1. For object-oriented software system design, it is necessary to improve the reusability of the system while supporting maintainability.
2, software reuse can improve the development efficiency of software, improve software quality, save development costs, appropriate reuse can also improve the maintainability of the system.
3. The principle of single duty requires that in a software system, a class is responsible for only one functional area.
4, open and close the principle requires a software entity should be opened to the extension, the modification is closed, that is, do not modify the source code based on the expansion of a system behavior.
5. The principle of substitution on the Richter scale can be expressed in the software if the base class object can be used, its subclass object must be able to be used.
6, dependence reversal principle requires that the abstraction should not rely on the details, the details should be dependent on the abstraction; To program for the interface, do not program for the implementation.
7, the principle of interface isolation requires the client should not rely on those it does not need to interface, some large interfaces will be refined into some small interface for the client to use.
8. The principle of synthetic multiplexing requires that you use object combinations as much as possible, rather than using inheritance.
9. The Dimitri Law requires that a software entity should interact with the other entities as little as possible.


7 Object-Oriented design principles

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.