Seven design principles for Java

Source: Internet
Author: User

1. Opening and closing principle (Open Close Principle)

Definition: A software entity such as classes, modules, and functions should be open to extensions and closed for modification.

Open-closed principle means that when you design, always consider, try to make this class is good enough, write well do not go to modify, if the new requirements come, we add some classes will be finished, the original code can not move. This principle has two characteristics, one is "open for expansion" and the other is "closed for change". In the face of demand, changes to the program are made by adding new code, rather than changing the existing code. This is the spirit of the open-closed principle.

2. The principle of substitution on the Richter scale (Liskov Substitution Principle)

Definition 1: If for each object of type T1, there is an object O2 of type T2, so that all program P defined by T1 is replaced with O1 for all objects O2, the behavior of program p does not change, then type T2 is a subtype of type T1.

Definition 2: Subtypes must be able to replace their parent types.
Description: A software entity if you use a parent class, then it must apply to its subclasses, and it does not recognize the difference between the parent and subclass objects, that is, in the software, the parent class is replaced by its subclasses, the behavior of the program does not change
Example: In biological classification, penguins are a kind of bird, but in the programming world, penguins can't inherit birds. In object-oriented design, subclasses have all non-private behaviors and properties of the parent class, birds fly, but penguins don't fly, so penguins can't inherit birds.

Only if the subclass can replace the parent class, the function of the Software unit is not affected, the parent class can actually be reused, and the subclass can add new behavior on the basis of the parent class, it is the principle of the Richter substitution, which makes the inheritance reuse possible. It is because of the replaceable nature of the subtype that the module using the parent class type can be extended without modification, otherwise it will talk about extended open, modified close.

The principle of the Richter substitution is popular: Subclasses can extend the functionality of the parent class, but cannot change the original functionality of the parent class. It contains the following 4 levels of meaning:

1. Subclasses can implement the abstract methods of the parent class, but cannot override the non-abstract methods of the parent class.

2. Subclasses can add their own unique methods.

3. When a method of a subclass overloads a method of the parent class, the method's preconditions (that is, the parameter of the method) are more lenient than the input parameters of the parent class method.

4. When a method of a subclass implements an abstract method of the parent class, the method's post-condition (that is, the method's return value) is stricter than the parent class.

It looks incredible, because we will find that in our own programming often violates the Richter scale replacement principle, the program still runs well. So everyone will have this question, if I do not follow the Richter scale replacement principle will have what consequences?

The consequence is that the odds of your code writing will increase dramatically.

3. Dependency reversal principle (dependence inversion Principle)

Definition: High-level modules should not be dependent on the lower layers, both should rely on their abstraction; abstractions should not depend on detail; detail should be dependent on abstraction. Programming for interfaces, not programming for implementation

Relying on reverse is actually who do not rely on who, in addition to the agreed interface, we can be flexible. Dependency reversal can be said to be the object-oriented design of the logo, in which language to write the program is not important, if the writing is to consider how to focus on abstract programming rather than the details of programming, that the program all the dependencies are terminated in the abstract class or interface, that is, object-oriented design, which is the process of design. If the various parts or classes of the design depend on each other, this is a high degree of coupling, difficult to maintain and expand, which can not show the object-oriented benefits.

Depending on the reversal principle, like a team, a requirement group, a development group, a test group, a development group, and a test group are all faced with the same requirements, do their own work, rather than the test group according to the needs of the development team to do test cases, that is, the development Group and test group are directly facing the requirements group work, Everyone's purpose is the same, to ensure that the product on time on-line, the demand is not dependent on development and testing.

The dependency inversion principle is based on the fact that abstract things are much more stable relative to the variability of details. Structures built on the basis of abstraction are much more stable than structures built on the basis of detail. In Java, abstract refers to an interface or abstract class, the details are specific implementation classes, the use of interfaces or abstract classes to make good specifications and contracts, not to involve any specific operation, the task of presenting details to their implementation class to complete.

The main idea of the dependency inversion principle is interface-oriented programming, there are three ways to pass the dependency relationship, the above is the interface transfer, there are two ways to transfer: Construction method transfer and setter method transfer, I believe that using the spring framework, the dependence of the transfer mode must not be unfamiliar.

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

The low-level module should have an abstract class or interface as much as possible, or both.

The declaration type of a variable is as abstract a class or interface as possible.

Follow the Richter substitution principle when using inheritance.

In short, the principle of dependency inversion is that we should interface programming, understand the interface-oriented programming, also understand the dependency inversion.

4. Interface Isolation principle (Interface segregation Principle)

The meaning of the principle of interface isolation is: Establish a single interface, do not set up a huge bloated interface, as far as possible to refine the interface, the interface of the method as little as possible. That is, instead of trying to create a very large interface for all classes that depend on it, we need to create a dedicated interface for each class. In programming, it is more flexible to rely on a few dedicated interfaces than to rely on an integrated interface. Interface is a design-time external set of "contract", through the decentralized definition of multiple interfaces, can prevent the proliferation of foreign changes, improve the system flexibility and maintainability.

Speaking of which, many people will feel that the principle of interface isolation is similar to the principle of single responsibility, but it is not. One is that the principle of single responsibility focuses on responsibility, while the interface isolation principle focuses on the isolation of interface dependencies. Second, the principle of single responsibility is mainly constrained class, the next is the interface and method, it is the implementation and details of the program, and the interface isolation principle mainly constrains the interface interface, mainly for the abstract, the overall framework of the program for the construction.

When using the interface isolation principle to constrain the interface, the following points should be noted:

1. The interface is as small as possible, but there are limits. The refinement of the interface can improve the design flexibility is not a fact, but if too small, it will result in an excessive number of interfaces, resulting in complex designs. So be sure to be modest.

2. To customize the service for an interface-dependent class, expose only to the calling class the method it requires, and the method it does not need is hidden. A minimal dependency can be established only by focusing on providing a customized service for a module.

3. Improve cohesion and reduce external interaction. Enable the interface to do the most things with the least amount of method.

The use of interface isolation principle, must be moderate, the interface design too large or too small are not good. When designing interfaces, it is only when you spend more time thinking and planning that you can accurately practice this principle.

4. Combination/Aggregation multiplexing principle

It means to use synthesis and aggregation as much as possible instead of inheriting relationships to achieve reuse.
The principle is to use some existing objects inside a new object to make it part of the new object: The new object is reused for the purpose of the existing functionality by delegating to those objects.
In fact, the final place is to distinguish between "has-a" and "is-a" difference. Relative to composition and aggregation,
The disadvantage of inheritance is that all methods of the parent class are exposed to subclasses. If the parent class changes, the subclass also changes. When the aggregation is reused, it is less dependent on the other class.
Synthesis/polymerization multiplexing
① Advantages:
The only way for a new object to access the Component object is through the interface of the Component object;
This reuse is a black-box reuse because the inner details of the constituent objects are invisible to the new object;

This multiplexing supports packaging;
Less reliance is required for such reuse;
Each new class can focus on one task;
This reuse can be done dynamically at run time, and new objects can use a composition/aggregation relationship to delegate new responsibilities to the appropriate objects.
② Disadvantages:
A system that is reused in this way will have more objects to manage.

Inheritance Reuse
① Advantages:
The new implementation is easier because most of the functionality of the base class can be automatically entered into the derived class through the inheritance relationship;
It is easier to modify or extend inherited implementations.
② Disadvantages:
Inheritance reuse destroys wrappers, because inheritance exposes the implementation details of the base class to derived classes, which are also known as white-box multiplexing;
If the implementation of the base class changes, then the implementation of the derived class has to change;
Implementations inherited from the base class are static and cannot be changed at run time and are not flexible enough.
6. Dimitri (Law of Demeter)

The fundamental idea of the Dimitri Law is to emphasize the loose coupling between classes, the weaker the coupling between classes, the more beneficial the reuse, the more the weak-coupling class is modified, and the related classes are not affected, that is to say, the hiding of information facilitates the reuse of the software.

Since we began to touch programming, we have learned the general principles of software programming: low-coupling, high cohesion. Whether it is process-oriented programming or object-oriented programming, it is possible to increase the code reuse rate by minimizing the coupling between the modules. The advantages of low coupling are self-evident, but how do you program to do low-coupling? That's exactly what the Dimitri law is going to do.

The Dimitri rule is also known as the least known principle, which was first proposed by Ian Holland of the American Northeastern University in 1987. In layman's terms, it is a class that knows as little as possible about the classes it relies on. That is to say, for a dependent class, no matter how complex the logic, as far as possible to encapsulate the logic inside the class, outside the public method provided, not to disclose any information. The Dimitri rule also has a simpler definition: communicate only with direct friends. Let's start by explaining what a direct friend is: Each object has a coupling relationship with other objects, so long as there is a coupling between the two objects, we say that the two objects are friends. There are many ways of coupling, dependence, association, composition, aggregation and so on. In this case, we call the class in the member variable, method parameter, method return value as a direct friend, and the class appearing in the local variable is not a direct friend. In other words, unfamiliar classes are best not to appear inside the class as a local variable.

The bottom line is that one object should keep a minimum of knowledge of other objects.

7. Single Duty principle (Responsibility Principle)

Definition: Do not have more than one cause for class changes. In layman's terms, a class is responsible for only one responsibility, and there should only be one cause for it to change.

When it comes to the principle of single responsibility, many people will dismiss it. Because it's too easy. Inexperienced programmers who have never read design patterns and have never heard of a single principle of responsibility will consciously adhere to this important principle when designing software, because it is common sense. In software programming, no one wants to cause other functions to fail because a feature has been modified. The way to avoid this problem is to follow a single principle of responsibility. Although a single responsibility principle is so simple and considered common sense, even the program written by an experienced programmer can have code that violates this principle. Why is this happening? Because there is responsibility to spread. The so-called responsibility spread, is for some reason, the responsibility P is divided into finer granularity of responsibility P1 and P2.

The advantages of following a single responsibility are:

1. The complexity of the class can be reduced, and a class is responsible for only one responsibility, and its logic is certainly much simpler than the responsibility for a number of responsibilities;

2. Improve the readability of the class and improve the maintainability of the system;

3. The risk of change is reduced, the change is inevitable, if a single responsibility principle is well adhered to, when a function is modified, it can significantly reduce the impact on other functions.

One point to note is that the single responsibility principle is not only specific to object-oriented programming, so long as it is modular programming, it is necessary to follow this important principle.

Seven design principles for Java

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.