The opening and closing principle of s.o.l.i.d Five principles OCP

Source: Internet
Author: User

The opening and closing principle is described as:

Software entities (classes, modules, functions, etc.) should is open for extension and closed for modification.
Software entities (classes, modules, methods, and so on) should be open to extensions and closed to modifications, i.e. software entities should be extended without modification.

Open for extension (opening for extensions) means that when new requirements arise, you can extend the existing model to achieve the goal. The Close for modification (closed for modification) means that no modifications to the entity are allowed, and it is plain that the entities that need to perform the various actions should be designed without modification to achieve a variety of changes, and the principle of opening and shutting is conducive to project maintenance with minimal code.

English Original: http://freshbrewedcode.com/derekgreer/2011/12/19/solid-javascript-the-openclosed-principle/

Problem code

To illustrate this visually, let's give an example of the code that shows the question list dynamically (without using the open/closed principle).

//Problem type
var Answertype = {
choice:0,
Input:1
};

//Problem entity
function question (label, Answertype, Choices) {
return {
Label:label,
Answertype:answertype,
Choices:choices//The choices here is an optional parameter
};
}

var view = (function () {
//Render a question
function renderquestion (target, question) {
var questionwrapper = document.createelement (' div ');
Questionwrapper.classname = ' question ';

var Questionlabel = document.createelement (' div ');
Questionlabel.classname = ' Question-label ';
var label = document.createTextNode (Question.label);
Questionlabel.appendchild (label);

var answer = document.createelement (' div ');
Answer.classname = ' question-input ';

//Show different code according to different types: drop-down menu and input box
if (Question.answertype = = = Answertype.choice) {
var input = document.createelement (' select ');
var len = question.choices.length;
for (var i = 0; i < Len; i++) {
var option = document.createelement (' option ');
Option.text = Question.choices[i];
Option.value = Question.choices[i];
Input.appendchild (option);
}
}
Elseif (Question.answertype = = = Answertype.input) {
var input = document.createelement (' input ');
Input.type = ' text ';
}

Answer.appendchild (input);
Questionwrapper.appendchild (Questionlabel);
Questionwrapper.appendchild (answer);
Target.appendchild (Questionwrapper);
}

return {
// Render: function (target, questions) {
for (var i = 0; i < questions.length; i++) {
Ren Derquestion (target, questions[i]);
};
}
};
}) ();

var questions = [
question (' You used tobacco products within the last Da Ys? ', Answertype.choice, [' Yes ', ' No '],
question (' What medications is currently using? ', Answertype.input)
];

var questionregion = document.getElementById (' questions ');
View.render (questionregion, questions);

The above code, the View object contains a render method used to display the question list, display the time according to the different question type use different display way, A question contains a label and a problem type, as well as an option for choices (if the type is selected). If the problem type is choice then produce a drop-down menu based on the option, and if the type is input, simply show the input box.

The code has a limitation that if you add another question type, you need to modify the conditional statements in the renderquestion again, which is a clear violation of the open and closed principle.

Refactoring code

Let's refactor this code so that the new question type is allowed to extend the render capability of the view object without having to modify the code inside the View object.

First, create a generic questioncreator function:

function Questioncreator (spec, my) {
var that = {};

my = My | | {};
My.label = Spec.label;

My.renderinput =function () {
Throw "not implemented";
//Here Renderinput is not implemented, the main purpose is to let the respective problem type implementation code to cover the entire method
};

That.render =function (target) {
var questionwrapper = document.createelement (' div ');
Questionwrapper.classname = ' question ';

var Questionlabel = document.createelement (' div ');
Questionlabel.classname = ' Question-label ';
var label = document.createTextNode (Spec.label);
Questionlabel.appendchild ( label);

var answer = My.renderinput ();
// The Render method is the same coarse reasonable code
// The only difference is the above sentence my.renderinput ()
// Because different problem types have different implementations
Questionwrapper.appendchild (Questionlabel);
Questionwrapper.appendchild (answer);
return Questionwrapper;
};

return that;
}

If the combination of this code is to render a problem, and provide an renderinput method that is not implemented so that other functions can be overridden to use different problem types, we continue to look at the implementation code for each problem type:

function Choicequestioncreator (spec) {

var my = {},
that = Questioncreator (spec, my);

//Renderinput implementation of the choice type
My.renderinput =function () {
var input = document.createelement (' select ');
var len = spec.choices.length;
for (var i = 0; i < Len; i++) {
var option = document.createelement (' option ');
Option.text = spec.choices[i];
Option.value = spec.choices[i];
input.appendchild (option);
}

return input;
};

return that;
}

function inputquestioncreator (spec) {

var my = {},
that = Questioncreator (spec, my);

// My.renderinput = function () {
var input = Document.createelement (' input ');
Input.type = ' text ';
return input;
};

return that;
}

The Choicequestioncreator function and the Inputquestioncreator function correspond to the renderinput implementation of the drop-down and input input boxes, respectively, by internally invoking the unified Questioncreator (spec, my Then returns that object (the same type, OH).

The code for the View object is very fixed.

var view = {
function (target, questions) {
for (var i = 0; i < questions.length; i++) {
Target.appendchild (Questions[i].render ());
}
}
};

So we just need to do this when we declare the problem, OK:

var questions = [
Choicequestioncreator ({
Label: ' Are you used tobacco products within the last of the days? ',
Choices: [' Yes ', ' No ']
}),
Inputquestioncreator ({
Label: ' What medications is you currently using? '
})
];

The final use of code, we can use:

var questionregion = document.getElementById (' questions ');

View.render (questionregion, questions);

function Questioncreator (spec, my) {
var that = {};

my = My | | {};
My.label = Spec.label;

My.renderinput =function () {
Throw "not implemented";
};

That.render =function (target) {
var questionwrapper = document.createelement (' div ');
Questionwrapper.classname = ' question ';

var Questionlabel = document.createelement (' div ');
Questionlabel.classname = ' Question-label ';
var label = document.createTextNode (Spec.label);
Questionlabel.appendchild (label);

var answer = My.renderinput ();

Questionwrapper.appendchild (Questionlabel);
Questionwrapper.appendchild (answer);
return questionwrapper;
};

return that;
}

function Choicequestioncreator (spec) {

var my = {},
that = Questioncreator (spec, my);

My.renderinput =function () {
var input = document.createelement (' select ');
var len = spec.choices.length;
for (var i = 0; i < Len; i++) {
var option = document.createelement (' option ');
Option.text = Spec.choices[i];
Option.value = Spec.choices[i];
Input.appendchild (option);
}

return input;
};

return that;
}

function Inputquestioncreator (spec) {

var my = {},
that = Questioncreator (spec, my);

My.renderinput =function () {
var input = document.createelement (' input ');
Input.type = ' text ';
return input;
};

return that;
}

var view = {
Render: function (Target, Questions) {
for (var i = 0; i < questions.length; i+ +) {
Target.appendchild (Questions[i].render ());
}
}
};

var questions = [
Choicequestioncreator ({
Label: ' You used tobacco The last of the products within ",
Choices: [' Yes ', ' No ']
}),
Inputquestioncreator ({
Label: ' What Medicati ONS is you currently using? '
})
];

var questionregion = document.getElementById (' questions ');

View.render (questionregion, questions);

Some of the technical points are applied to the above code, so let's look at them individually:

    1. First, the creation of the Questioncreator method allows us to use the template method pattern to delegat the functionality of the problem to the extended code renderinput for each problem type.
    2. Second, we replaced the constructor property of the previous question method with a private spec attribute because we encapsulated the render behavior and no longer needed to expose these properties to external code.
    3. Thirdly, we create an object for each problem type for the respective code implementation, but each implementation must contain the Renderinput method to overwrite the Renderinput code in the Questioncreator method, which is what we often call the policy pattern.

By refactoring, we can remove the enumeration answertype of the unnecessary problem type, and let choices be the required parameter for the Choicequestioncreator function (the previous version is an optional parameter).

Summarize

Refactoring the later version of the View object can be very clear to the new extension, for different problem types to extend the new object, and then declare the questions collection when the specified type on the line, the view object itself no longer modify any changes, so as to achieve the requirements of the open and close principle.

The opening and closing principle of s.o.l.i.d Five principles OCP

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.