What is the meaning and reasoning behind the Open/Closed Principle?

后端 未结 14 1202
死守一世寂寞
死守一世寂寞 2020-12-02 08:31

The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. What does this mean, and why is i

14条回答
  •  醉话见心
    2020-12-02 08:48

    Software entities should be open for extension but closed for modification

    That means any class or module should be written in a way that it can be used as is, can be extended, but neve modified

    Bad Example in Javascript

    var juiceTypes = ['Mango','Apple','Lemon'];
    function juiceMaker(type){
        if(juiceTypes.indexOf(type)!=-1)
            console.log('Here is your juice, Have a nice day');
        else
            console.log('sorry, Error happned');
    }
    
    exports.makeJuice = juiceMaker;
    

    Now if you want to add Another Juice type, you have to edit the module itself, By this way, we are breaking OCP .

    Good Example in Javascript

    var juiceTypes = [];
    function juiceMaker(type){
        if(juiceTypes.indexOf(type)!=-1)
            console.log('Here is your juice, Have a nice day');
        else
            console.log('sorry, Error happned');
    }
    function addType(typeName){
        if(juiceTypes.indexOf(typeName)==-1)
            juiceTypes.push(typeName);
    }
    function removeType(typeName){
      let index = juiceTypes.indexOf(typeName)
        if(index!==-1)
            juiceTypes.splice(index,1);
    }
    
    exports.makeJuice = juiceMaker;
    exports.addType = addType;
    exports.removeType = removeType;
    

    Now, you can add new juice types from outside the module without editing the same module.

提交回复
热议问题