The six principles of object-oriented (recommended)

Source: Internet
Author: User

It is difficult to make the software very flexible and easy to maintain. Flexible software His structure is complex and difficult to maintain. The key lies in how to deal with the two, making greater than the loss. The design and development of software should follow the following six major principles:
1. OCP
Full name: "Open-closed Principle" open-closed principle

Description: Open for extension, close for modification.
Advantages: The system designed according to the OCP principle reduces the coupling between each part of the program, and its adaptability, flexibility and stability are better. When existing software systems need to add new functionality, there is no need to modify the abstraction layer as the basis of the system, simply attach the new module on the original basis to achieve the required functionality. The added new modules have no effect on the original modules or have minimal impact, so there is no need to re-test the original modules.
How to implement the "open-close" principle
In object-oriented design, it is not allowed to change the abstraction layer of the system, but the implementation layer of the system is allowed to extend. In other words, define a once and for all abstract design layer, allowing as many behaviors as possible to be implemented at the implementation level.
The key to solving the problem lies in abstraction, which is the first core essence of object-oriented design.
The abstraction of a thing is essentially a generalization of its essence. Abstract let us seize the most important things, from a higher level to think. This reduces the complexity of thinking, and we don't have to think about that much at the same time. In other words, we encapsulate the nature of things and see no details.
In object-oriented programming, by means of abstract classes and interfaces, the characteristics of specific classes are defined as abstract layers, relatively stable, without change, so as to satisfy the "close to modify", and the concrete classes derived from abstract classes can change the behavior of the system, thus satisfying the "open to extended".
When you extend an entity, you do not have to change the source code or the binaries of the software. The key is abstraction.

2. LSP
Full Name: "Liskov Substitution Principle" on the Richter substitution principle
Description: Subtypes must be able to replace their base types. A software entity if you are using a base class, then when you replace the base class with a subclass that inherits the base class, the behavior of the program does not change. The software entity does not perceive the difference between a base class object and a subclass object.
Advantages: It is easy to implement the interchange of subclasses under the same parent class, and the client can be unaware.

3. DIP
Full name: "Dependence inversion Principle" dependency inversion principle

Description: To rely on abstraction, do not rely on specifics. The client relies on abstract coupling.
Abstraction should not be dependent on detail; details should be dependent on abstraction;
To program for the interface, do not program for implementation.
Pros: Using the dependencies created by traditional procedural programming, the policy relies on detail, which is bad because the strategy is affected by the change in detail. The dependency inversion principle makes the detail and strategy dependent on the abstraction, and the stability of the system determines the stability.
How to do dependency inversion?
Coupling in an abstract way is the key to relying on the reversal principle. Abstract coupling relationships always involve concrete classes inheriting from abstract classes, and it is necessary to ensure that any reference to the base class can be converted to its subclasses, so the Richter substitution principle is based on the principle of reversal.
Although coupling at the level of abstraction is flexible, it also brings additional complexity, and if the likelihood of a specific class change is very small, then the benefits of an abstract coupling can be very limited, which can be better with concrete coupling.
Hierarchical: All well-structured object-oriented architectures have a clear hierarchical definition, with each level providing a cohesive set of services to the outside through a well-defined, controlled interface.
Dependent on abstraction: the recommendation does not depend on a specific class, that is, all dependencies in a program should terminate in an abstract class or interface. Try to do the following:
1. Any variable should not hold a pointer or reference to a specific class.
2. No class should derive from a specific class.
3. No method should overwrite an already implemented method in any of its base classes.

4. ISP
Full name: "Interface segregation Principle" interface isolation principle

Description: An interface that uses multiple-specificity features is always better than using a single total interface. From the perspective of a customer class, the dependency of a class on another class should be based on the minimum interface. An overly bloated interface is a pollution to the interface and should not force customers to rely on methods that they do not use.
Pros: When a software system function is extended, the modified pressure is not propagated to other objects.
How to implement the principle of interface isolation
Users should not be forced to rely on methods that they do not use.
1, the use of delegated separation interface.
2, the use of multi-inheritance separation interface.

5. CARP or CRP
Full name: "Composit
e/aggregate Reuse Principle "synthesis/polymerization multiplexing principle or" Composite reuse Principle "The principle of synthetic multiplexing
Note: If some functionality of the new object has already been implemented in another object that has already been created, try to use the functionality provided by other objects as part of the new object rather than recreating it yourself. The new objects are multiplexed into the existing functionality by delegating to these objects.
In short, use composition/aggregation as much as possible, and do not use inheritance as much as possible.
Advantages:
1) The only way to access an ingredient object from a new object is through the interface of the Component object.
2) This reuse is a black-box reuse because the inner details of the constituent objects are invisible to the new object.
3) This multiplexing supports packaging.
4) This multiplexing requires less reliance.
5) Each new class can focus on one task.
6) This multiplexing can be performed dynamically during runtime, and new objects can dynamically reference objects of the same type as the constituent objects.
7) As a means of reuse can be applied to almost any environment.
Disadvantages:
Is that there will be more objects in the system to be managed.

6. LOD or LKP
Full name: "Law of Demeter" Dimitri Principle or "Least knowledge Principle" minimum knowledge principle

Description: The object and object should be associated with as few methods as possible to avoid the intricate relationships.
How to implement Dimitri law
The main purpose of Dimitri Law is to control the overload of information, in the application of the system design should pay attention to the following points:
1) in the division of classes, a class with weakly coupled should be created. The weaker the coupling between classes, the more beneficial it is to reuse.
2) in the class structure design, each class should minimize the member's access rights. A class should not public its own property, but should provide a way to give value and assignment to the outside world to access its properties indirectly.
3) in the design of the class, whenever possible, a class should be designed to be invariant class.
4) on references to other objects, a class's reference to other objects should be minimized.


There is also a single principle of responsibility:

Introduction to the SRP (srp--single-responsibility Principle): As far as a class is concerned, one should only focus on doing one thing and only a reason that causes it to change
。 The so-called duty, we can understand his function, is that the design of this kind of function should be only one, not two or more. It can also be understood that the reason for the reference change, when you find that there are two changes that will require us to modify the class, then you have to consider the withdrawal of this class. Because responsibility is an axis of change, when demand changes, the change reflects the change in the class's responsibilities. Use SRP Note: 1, a reasonable class, should have only one cause of its change, that is, a single duty;
2. It is unwise to apply the SRP or other principles without any indication of change;
3, in the actual change in demand should be applied to the principles of SRP to reconstruct the code;
4. The use of test-driven development will force us to separate unreasonable code before the design stinks;
5. If the test does not force separation of duties, the stench of rigidity and fragility becomes strong, then the code should be refactored with the facade or proxy pattern; SRP Pros: Eliminate coupling and reduce code rigidity due to changes in demand.


you do not have to strictly abide by these principles, and you will not be punished by a religious penalty against them. But you should think of these principles as alarms, and if you violate one of them, the alarm will ring.
-----Arthur J.riel
(1) All data should be hidden inside the class in which it resides.
(2) The consumer of a class must depend on the common interface of the class, but the class cannot rely on its consumer. P15
(3) Minimize the message in the class's protocol.
(4) Implement the most basic public interfaces understood by all classes [for example, copy operations (deep and shallow copies), equality judgments, correct output content, parsing from ASCII descriptions, etc.]. P16
(5) Do not place implementation details (such as private functions that place common code) in the public interface of the class.
if the two methods of a class have a common code, you can create a private function that prevents these common code.
(6) Do not disturb the public interface of the class with something that the user cannot use or is not interested in. P17
(7) The class should be 0 coupled, or only the coupling relationship should be exported. That is, one class has nothing to do with another class, or it only uses operations in the public interface of another class. P18
(8) A class should only represent a critical abstraction.
all classes in the package should be closed together for changes of the same class nature. If a change affects one package, it will affect all classes in the package, without any impact on the other packages.
(9) Put the relevant data and behavior in a centralized position.
designers should be aware of objects that get data from other objects through operations such as get. This type of behavior implies that the rule of thumb has been violated.
(10) Placing irrelevant information in another class (i.e., non-communicating behavior). P19
to rely on in a stable direction.
(11) Ensure that the abstract concept you are modeling is a class, not just the role that the object plays. P23
(12) in the horizontal direction as far as possible uniformly distributed system functions, namely: according to design, the top class should be unified to share the work.
(13) Do not create an almighty class/object in your system. Be especially careful with classes whose names contain driver, Manager, System, Susystem.
plan an interface instead of implementing one.
(14) Be cautious about classes that have a large number of access methods defined in the public interface. A large number of access methods means that the relevant data and behavior are not centrally stored.
(15) Be cautious about classes that contain too many non-communicating behaviors.
another manifestation of this problem is that many get and set functions are created in the public interface of the class in your application.
(16) in an application that is composed of an object-oriented model that interacts with the user interface, the model should not be dependent on the interface, and the interface should be dependent on the model.
(17) as much as possible according to the real World modeling (we often violate this principle in order to comply with the principle of system function distribution, avoid the principle of universal class and the principle of centralizing the relevant data and behavior).
(18) Remove unwanted classes from your design.
in general, we will downgrade this class to an attribute.
(19) Remove the class outside the system.
classes outside the system are characterized by the abstract view that they only send messages to the system domain but do not accept messages from other classes in the system domain.
(20) Do not turn the operation into a class. Challenge any class whose name is a verb or derive an automatic word, especially one that has a meaningful behavior. Consider whether that meaningful behavior should be migrated to a class that already exists or has not yet been discovered.
(21) We often introduce proxy classes when creating an analytic model of an application. In the design phase, we often find that many agents are useless and should be removed.
(22) Minimize the number of collaborators in the class.
The number of other classes used by a class should be as few as possible.
(23) Minimize the number of messages that are passed between classes and collaborators.
(24) minimizing the amount of collaboration between classes and collaborators, i.e. reducing the number of different messages passed between classes and collaborators.
(25) minimizing the fanout of classes, i.e. reducing the number of messages that are defined by the class and the number of messages sent
(26) If the class contains an object of another class, the containing class should send a message to the contained object. That is, including relationships always means using relationships.
Most of the methods defined in the (27) class should use most data members for most of the time.
(28) The number of objects contained in the class should not exceed the developer's short-term memory capacity. This number is often 6.
when a class contains more than 6 data members, you can divide the logically related data members into a group, and then use a new containing class to contain the set of members.
(29) The system function is distributed vertically in a narrow and deep inheritance system.
(30) When implementing semantic constraints, it is best to implement them according to the class definition. This often leads to a class overrun, in which case the constraints should be implemented in the behavior of the class, usually implemented in constructors, but not required.
(31) When implementing semantic constraints in the constructor of a class, the constraint test is placed in the deepest inclusion level allowed in the domain of the constructor.
(32) The semantic information on which the constraint relies is often changed, preferably in a centralized 3rd-party object
(33) If the semantic information on which the constraint depends is rarely changed, it is best to distribute it in the various classes involved in the constraint.
(34) A class must know what it contains, but cannot know who contains it.
(35) objects that share literal scope (that is, are contained by the same class) should not be used in relation to each other
(36) Inheritance should only be used to model the hierarchical structure of a specific hierarchy.
(37) Derived classes must know the base class, and the base class should not know any information about their derived classes.
(38) All data in the base class should be private and do not use protection data. The designer of a class should never put something that the user of the class does not need in the public interface.
(39) In theory, the hierarchy system of inheritance should be deeper, the deeper the better.
(40) In practice, the depth of the hierarchy of inheritance should not exceed the short-term memory ability of an ordinary person. A widely accepted depth value is 6.
(41) All abstract classes should be base classes
(42) All base classes should be abstract classes
(43) Put the generality of data, behavior and/or interface as far as possible to the high end of the inheritance hierarchy system.
(44) If two or more classes share common data (but no public behavior), then the public data should be placed in a class, and each class that shares the data contains this class.
(45) If two or more classes have common data and behavior (that is, methods), each of these classes should inherit from a common base class that represents the data and methods.

(46) If two or more classes share a common interface (that is, messages, not methods), they should inherit from a common base class only if they need to be used in a polymorphic manner.

(47) It is generally wrong to analyze the display of object types in a split-case analysis. In most of these cases, the designer should use polymorphism.
(48) analysis of the display of attribute values is often incorrect. Classes should be decoupled into an inheritance hierarchy, and each property value is transformed into a derived class.
(49) Do not model the dynamic semantics of a class by inheriting relationships. Attempts to model dynamic semantics with static semantic relationships can result in switching types at run time.
(50) do not turn the object of the class into a derived class. Be careful with any derived class that has only one instance.
(51) If you feel the need to create a new class at run time, take a step back and recognize that you are creating an object. Now, summarize these objects into one class.
(52) It should be illegal to overwrite a method in a base class with an empty method (that is, a method that does nothing) in a derived class.
(53) Do not confuse optional inclusions with the need for inheritance. Modeling an optional inclusion into a class where inheritance can lead to flooding.
(54) When creating an inheritance hierarchy, try to create a reusable framework, rather than a reusable component.
(55) If you use multiple inheritance in your design, let's say you made a mistake. If you don't make a mistake, you need to try to prove it.
(56) As long as inheritance is used in object-oriented design, ask yourself two questions: (1) is the derived class A special type of the thing it inherits from? (2) is the base class part of a derived class?
(57) If you find multiple inheritance relationships in an object-oriented design, make sure that no base class is actually a derived class of another base class.
(58) in object-oriented design, if you need to make a choice between an inclusive relationship and an associated relationship, select include relationship.
(59) Do not use global data or global functions for the thinning of objects in a class. You should use class variables or class methods.
(60) object-oriented designers should not let physical design guidelines undermine their logical design. However, in the process of making decisions on logical design, we often use physical design guidelines.
(61) Do not bypass the public interface to modify the state of the object.  

Original Digest from: http://blog.csdn.net/GOALSTAR/article/details/3735612

The six principles of object-oriented (recommended)

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.