Elegant design patterns trip - the principle of opening and closing

Opening speech

Recently, many small partners private letter asked me how to write a high force grid makes one look like a good programmer to write code? What was the code is the code standard was it? How to become a team code standards? ... and so on we have to consult some front-end code written in terms of the problem, so we began our design patterns trip.

Mentality

++ good code like porridge, boil out all the time with +

Background

In software development, in order to improve maintainability and reusability of the software system, the software increases the flexibility and scalability, programmers try to develop a program in accordance with the principles 7, thereby enhancing the efficiency of software development, software development savings costs and maintenance costs. We will in the next few sections in order to introduce these seven principles, this section introduces the principle of opening and closing.

Open Closed Principle

What is the principle of opening and closing?
  • Full name: the original opening and closing
  • 简称:ocp(Open Closed Principle)
  • Definition: Software entities (projects divided into modules, classes, and interfaces, methods, etc ...) should be extensible
How to understand the principle of opening and closing of the opening and closing?
  • On -> entity that is to expand the software is open
    can be expanded when the function for a module. When needs change, we need to expand it to meet new requirements
    for example
    such as "Brick" is that we have a good package class that we do not need to change his form and structure, we just built according to demand tall buildings or build walls. It can be considered a "brick" is the demand for extension is open.
  • Closed -> i.e., changes in the software entity is enclosed
    source code or binary code module when extended, without changing the module. If this module has been clearly defined, stable and efficient are a number of other modules, the relationship of this module provides an interface for use on its behalf template.
    For example
    than my notebook by our CPU, motherboard, memory, and the like, they are not tightly coupled together. If it is tightly coupled together in series equivalent, then a really bad one is not so that the computer will need to re-purchase is clearly unreasonable. So when our memory is broken, we just need to be more content can also re-use the current node in parallel with similar damage does not affect other nodes.
The meaning of the principle of opening and closing?
  • When the application requirements change, without modifying the source code of a software entity or binary code, you can extend the functionality of the modules, to meet the new demand
Opening and closing of the role and significance of the principle (why should follow the principle of opening and closing)?

Open Closed Principle is the ultimate goal of object-oriented programming, he is a software entity has a certain practicality and flexibility along with stability and continuity.

  • Impact on software testing
    software follows the principles of the open side of the case, software testing only need to test the code to expand on it, because crude oil is still able to function properly test code
  • Improve the code reusability
    smaller the particle size, the greater the possibility of being multiplexed; in object-oriented programming, and the atomic abstract programming can improve code reusability.
  • You can improve software maintainability of
    compliance with the principle of opening and closing software, high stability and strong continuity, making it easy to expand and maintain
Realization of the principle of opening and closing (how to achieve the principle of opening and closing)

Abstract constraints

Design principles and object-oriented programming ideas actually complement each other, it will be played by the abstraction, encapsulation, inheritance, polymorphism. Abstract is a generic description of a set of things, there is no specific implementation, also said he could have a lot of possibilities, can vary with changes in demand. Thus, the interface or by a set of abstract classes can constrain behavior may change, and enables extended open wherein three meanings:

  • Abstract class interface or by diffusion constraints, the extended boundary is defined, the method does not exist in the public interface or abstract class is not allowed.
  • Parameter type, reference objects to make use of interface or abstract class, not the implementation class, which is a major requirement to replace the principle of Xianxian Richter (Late article update)
  • Abstraction layer as stable as possible, once it is determined not to modify

Metadata Control module behavior

Programming is a drudge, will be the same programmer is also a very lazy types. Good programmers will try to use metadata to control programs, reduce duplication of development. What is metadata? Used to describe the data environment and the data, it is popular configuration parameters, parameters can be obtained from the file, in the database can also be obtained

Team project agreement

In a team, the establishment of project standards is very important, because the standard is that all developers must comply with the agreement, for the project, the convention over configuration. This is done more efficiently than through restraint interface or abstract class, with no trace of impact scalability.

Deep understanding of the packaging change

It has two meanings package changes (not the same as the sampling and abstract, bad abstract no more uncomfortable than abstract)

  • The same change package to an interface or abstract class
  • The different variations of the package to a different interface or abstract class, there are two different variations should not appear in the same abstract class or an interface. Packaging changes, which is protected by the changes, expected to find there is a change or an unstable point, we create a stable interface points for these changes
The face of development (usage scenarios)
  • Requirements: commodity list, if it is the type of men, merchandise blue background color, then click the pop-up men price; if it is women, commodity red background color, click on the pop-up women's brands.

Normal code (for process development)

if (commodity.type === ‘男装‘) {
    commodity.css(background, blue); 
} else { 
    commodity.css(background, red); 
    
} 
// 点击事件的函数中 
if (commodity.type === ‘男装‘) { 
    // 弹出价格 
    alert(commodity.price); 
} else { 
    // 弹出品牌
    alert(commodity.brand); 
}
  • Changes in demand: Product little sister ran to inform add a commodity type, children's clothing, merchandise with a yellow background color, then click on the pop-up sales of children's clothing.
if (commodity.type === ‘男装‘) { 
    commodity.css(background, blue); 
} else if (commodity.type === ‘女装‘) {
    // 修改点1 增加女装类型判断 
    commodity.css(background, red); 
} else { 
    // 修改点2 增加童装html渲染处理 
    commodity.css(background, yellow); 
} 
// 点击事件的函数中 
if (commodity.type === ‘男装‘) {
    // 弹出价格 
    alert(commodity.price); 
} else if (commodity.type === ‘女装‘) { 
    // 修改点3 增加女装类型判断 
    // 弹出价格 
    alert(commodity.brand);
} else { 
    // 修改点4 增加童装点击处理 
    // 弹出销量 
    alert(commodity.sales); 
}

France has been on the code written estimate there will be a lot of peers to write this, in fact, small partners psychology also very nervous, that code is not the first technology degree, and then the second new demand yet I still judge so add it? How can a third do not have to modify the code yourself how easy some of it?

Then we take a look at the code to write a line with the principle of opening and closing in accordance with this demand so that we feel

// 抽象封装getManager
function getManager(commodity){
    if (commodity.type === ‘男装‘) return MaleManager; 
    if (commodity.type === ‘女装‘) return FemaleManager;
}
let MaleManager = { 
    Settingbackground: function () { 
        commodity.css(background, blue); 
    }, 
    Prompt: function () { 
        // 弹出价格 
        alert(commodity.price); 
    } 
}; 
let FemaleManager = { 
    Settingbackground: function () { 
        commodity.css(background, red); 
    }, 
    Prompt: function () { 
    // 弹出品牌 
    alert(commodity.brand);
    } 
};

OK, the amount of code like much, more than a few objects and methods. . . But I have not felt the readability of the code has increased, the degree of respect to force the grid is not above a little better than watching; good now so lovely sister again put the needs of the product -> "requirement plus a children's clothing."

// 抽象封装getManager
function getManager(commodity){
    if (commodity.type === ‘男装‘) return MaleManager; 
    if (commodity.type === ‘女装‘) return FemaleManager;
    if (commodity.type === ‘童装‘) return ChildManager;
}
let MaleManager = { 
    Settingbackground: function () { 
        commodity.css(background, blue); 
    }, 
    Prompt: function () { 
        // 弹出价格 
        alert(commodity.price); 
    } 
}; 
let FemaleManager = { 
    Settingbackground: function () { 
        commodity.css(background, red); 
    }, 
    Prompt: function () { 
    // 弹出品牌 
    alert(commodity.brand);
    } 
};
let ChildManager = { 
    Settingbackground: function () { 
        commodity.css(background, yellow);
    }, 
    Prompt: function () { 
        // 弹出销量 
        alert(commodity.sales); 
    } 
};

We can see the need for any original Men Women business we do not need to be modified, so we conducted a closed process, we need to expand a children's clothing, code designed in accordance with the principle of opening and closing, only a point to modify, amend the place can also predict, you can modify the routing method getManager (modified here actually avoided); then add a manager to children's clothing.

to sum up

In fact, I write code or phrase slogan: good code like porridge, so when we got business needs, have to learn to think with time all boil out, when the serious thinking of to go to write code;! we must be open for business needs good will and serious understanding of business needs, and then facilitate their better abstraction analysis business, but also allows us to more clearly aware of the package when it is constant is change those those are closed those to expand ... design pattern is a cosmetic programmer depends on how you are wearing makeup ...

To help make learning easy, efficient and free for everyone to share a large number of resources to help you in becoming a full stack engineers, architects and even the way through the clutter. We are here to recommend a full-stack Learning Exchange front-end circle: ?? 947,552,909, or wx:.? Fxq1221623 welcome everyone into the group discussions and exchange learning exchanges and common progress?.

Some people are passionate about learning, but the lack of direction, and in the vast ocean of knowledge in the seemingly endless, at this time the most important thing is to know which technologies need to focus grasp, avoid doing useful work, the limited energy and to maximize state of.

Finally wish all encounter a problem and do not know how to do the front-end programmers, I wish you all in the future work and interview all the best.

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/104189654
Recommended