. NET Senior architect 0005 Architect's Road (4)---Object-oriented design principles

Source: Internet
Author: User

1 OO design principles

The use of object-oriented analysis and design ideas, for us to analyze and solve problems to provide a new way of thinking. After we get the demand (omit Ooa, complete later), the next question is: How to object-oriented design of the system?

According to the theory of software engineering, the core problem that object-oriented design solves is maintainability and reusability. Especially maintainability, which is an important factor affecting the software life cycle, usually, the maintenance cost of software is much larger than the initial development cost.

A poorly maintainable software design, commonly referred to as the "stink", is formed by a number of reasons: too stiff, too fragile, with a low reuse rate, or too high a viscosity. On the contrary, a good system design should be flexible, extensible, reusable, pluggable. In the 80-90 years of 20th century, many industry experts continue to explore object-oriented software design methods, and put forward some design principles. These design principles can significantly improve the maintainability and reusability of the system and become our guiding principle for object-oriented design:

1. single Duty principle SRP

Each class should focus only on doing one thing.

2. "open-close" principle OCP

Each class should be open to extensions and closed for modification.

3. The Richter substitution principle LSP

To avoid illegal or degrading methods that result in derived classes, a user of a base class should not need to know about this derived class.

4. dependency Reversal Principle dip

Instead of relying on interfaces and abstract classes to replace dependent, concrete classes that are prone to change.

5. interface Isolation principle ISP

The client should be provided with the smallest possible interface, rather than providing a large interface.

Among them, the "open-close" principle is the cornerstone of object-oriented reusable design, and other design principles are the means and tools to realize the "open-close" principle.

I will give you a brief explanation.

2 Single Duty principle SRP (single-responsibility Principle) 2.1 What is a single duty

A single function is to mean that a class should focus on doing one thing. There are problems in real life: "A person may be a number of jobs, even if these responsibilities are not related to each other, then he may not be able to do all the duties within the matter, so it is better to specialize." "When designing a class, we should follow this principle: a single duty.

We take calculator programming as an example:

In some people's eyes, the calculator is a thing, is a whole, so it is to abstract this requirement, the final design as a calculator class, the code is as follows:

Class calculator{

Public String Calculate () {

Console.Write ("Please input the first number:");

String strNum1 = Console.ReadLine ();

Console.Write (Please input the operator: ");

String stropr= console.readline ();

Console.Write ("Please input the second number:");

String strNum2 = Console.ReadLine ();

String strresult = "";

if (Stropr = = "+") {

strresult = convert.tostring (convert.todouble (STRNUM1) + convert.todouble (strNum2));

}

else if (STROPR = = "-") {

strresult = convert.tostring (convert.todouble (STRNUM1)-convert.todouble (strNum2));

}

else if (STROPR = = "*") {

strresult = convert.tostring (convert.todouble (STRNUM1) * convert.todouble (strNum2));

}

else if (STROPR = = "/") {

strresult = convert.tostring (convert.todouble (STRNUM1)/convert.todouble (strNum2));

}

Console.WriteLine ("The result is" + strresult);

}

}

In addition, some people think: calculator is a shell and a combination of a processor.

Class appearance{

public int Displayinput (string &strnum1,string &stropr, string &strnum2) {

Console.Write ("Please input the first number:");

STRNUM1 = Console.ReadLine ();

Console.Write (Please input the operator: ");

Stropr= Console.ReadLine ();

Console.Write ("Please input the second number:");

strNum2 = Console.ReadLine ();

return 0;

}

public string Displayoutput (string strresult) {

Console.WriteLine ("The result is" + strresult);

}

}

Class processor{

public string Calculate (String strnum1,string stropr, string strNum2) {

String strresult = "";

if (Stropr = = "+") {

strresult = convert.tostring (convert.todouble (STRNUM1) + convert.todouble (strNum2));

}

else if (STROPR = = "-") {

strresult = convert.tostring (convert.todouble (STRNUM1)-convert.todouble (strNum2));

}

else if (STROPR = = "*") {

strresult = convert.tostring (convert.todouble (STRNUM1) * convert.todouble (strNum2));

}

else if (STROPR = = "/") {

strresult = convert.tostring (convert.todouble (STRNUM1)/convert.todouble (strNum2));

}

return strresult;

}

}

Why did you do it? Because the shell and the processor are two responsibilities, it is very easy to change the factors of demand, so put them in a class, contrary to the principle of single responsibility.

For example, the user may make the following requirements for the calculator:

First, the "addition", "subtraction", "multiplication" and "division" have been realized at present, and many operations such as "exponentiation" and "root" may appear later.

Second, the human-machine interface is too simple now, it may also be a Windows Calculator-style interface or Mac calculator-style interface.

So, splitting a class calculator into two classes appearance and processor makes it easier to respond to demand changes. If the interface needs to be modified, then modify the Appearance class, and if the processor needs to be modified, then modify the processor class.

Let's give an example of an email. What we usually receive is a letter, which actually consists of two parts: the mail header and the mail body. e-mail encoding requirements conform to the RFC822 standard.

The first design approach is this:

Interface Iemail {

public void Setsender (String sender);

public void Setreceiver (String receiver);

public void SetContent (String content);

}

Class Email implements Iemail {

public void Setsender (String sender) {//set sender;}

public void Setreceiver (String receiver) {//set receiver;}

public void SetContent (String content) {//set content;}

}

This design is problematic because both the message header and the mail body have the potential to change.

1, the message header of each domain encoding, may be BASE64, may also be QP, and the number of domains is not fixed.

2. The message contents in the message body may be plaintext type, HTML type, or even streaming media.

The so-called first design approach violates the single principle of responsibility, which encapsulates two possible causes of change.

We have improved on the basis of a single responsibility principle and become the second design method:

Interface Iemail {

public void Setsender (String sender);

public void Setreceiver (String receiver);

public void SetContent (icontent content);

}

Interface Icontent {

Public String getasstring ();

}

Class Email implements Iemail {

public void Setsender (String sender) {//set sender;}

public void Setreceiver (String receiver) {//set receiver;}

public void SetContent (Icontent content) {//set content;}

}

Some data interpret a single duty as: "There is only one cause for it to change". This explanation is equivalent to "focus on doing one thing". If a class does two things at the same time, both things can cause it to change. In the same way, if there is only one cause for it to change, then this class can only do a thing.

2.2 Use of the single responsibility principle

How is the scale of a single responsibility principle mastered? How can I know whether to split or not? The principle is simple: demand decisions. If you need a calculator that never has the appearance and the possibility of a processor change, then you should abstract it into a whole calculator; If you need a calculator, the shell and the processor are likely to change, then you must detach it for the shell and the processor. There can be only one reason for the calculator to change.

The principle of single responsibility aggregates the same responsibilities and avoids the dispersion of the same duties into different classes, which can control change, limit change to one place, and prevent a "ripple effect" that causes more local changes due to changes in one place. The principle of single responsibility actually eliminates the coupling between objects, and avoids a class taking on too much responsibility. A single responsibility is not to say that a class has only one method, but a single function.

When we use a single principle of responsibility, keep the following in mind:

A, a reasonable design of the class, should have only one can cause it to change the reason, that is, a single duty, if there are multiple reasons can cause its change, it must be separated;

B, in the absence of signs of demand change, the application of SRP or other principles is unwise, because this will make the system very complex, the system consists of a bunch of small particles, which is nothing to find smoke;

C, when demand can be predicted or actually change, should use the SRP principle to refactor the code, experienced designers, architects are sensitive to possible changes in demand, design will be forward-looking.

. NET Senior architect 0005 Architect's Road (4)---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.