खोज…


परिचय

ओपन क्लोज प्रिंसिपल बताता है कि कोड का डिज़ाइन और लेखन इस तरह से किया जाना चाहिए कि मौजूदा कोड में न्यूनतम परिवर्तन के साथ नई कार्यक्षमता जोड़ी जाए। डिज़ाइन को एक तरह से किया जाना चाहिए ताकि नई कार्यक्षमता को नई कक्षाओं के रूप में जोड़ा जा सके, जो मौजूदा मौजूदा कोड को अपरिवर्तित रखे। क्लासेस, मॉड्यूल और फ़ंक्शंस जैसी सॉफ़्टवेयर इकाइयाँ एक्सटेंशन के लिए खुली होनी चाहिए, लेकिन संशोधनों के लिए बंद।

टिप्पणियों

हर सिद्धांत की तरह Open Close Principle केवल एक सिद्धांत है। एक लचीली डिज़ाइन बनाने में इसके लिए खर्च किया गया अतिरिक्त समय और प्रयास शामिल होता है और यह कोड की जटिलता को बढ़ाते हुए नए स्तर की शुरुआत करता है। इसलिए इस सिद्धांत को उन क्षेत्रों में लागू किया जाना चाहिए, जिनके बदलने की संभावना सबसे अधिक है। कई डिज़ाइन पैटर्न हैं जो हमें कोड को बदलने के बिना इसे बढ़ाने में मदद करते हैं, उदाहरण के लिए डेकोरेटर।

खुला सिद्धांत उल्लंघन

/* 
* This design have some major issues
* For each new shape added the unit testing
* of the GraphicEditor should be redone                      
* When a new type of shape is added the time
* for adding it will be high since the developer
* who add it should understand the logic
* of the GraphicEditor.
* Adding a new shape might affect the existing
* functionality in an undesired way, 
* even if the new shape works perfectly   
*/ 

class GraphicEditor {
    public void drawShape(Shape s) {
        if (s.m_type==1)
            drawRectangle(s);
        else if (s.m_type==2)
            drawCircle(s);
    }
    public void drawCircle(Circle r) {....}
    public void drawRectangle(Rectangle r) {....}
}

 class Shape {
     int m_type;
 }

 class Rectangle extends Shape {
     Rectangle() {
         super.m_type=1;
     }
 }

 class Circle extends Shape {
     Circle() {
         super.m_type=2;
     }
 }

ओपन क्लोज प्रिंसिपल सपोर्ट

/*
* For each new shape added the unit testing
* of the GraphicEditor should not be redone
* No need to understand the sourcecode
* from GraphicEditor.
* Since the drawing code is moved to the
* concrete shape classes, it's a reduced risk
* to affect old functionallity when new
* functionallity is added.
*/ 
class GraphicEditor {
     public void drawShape(Shape s) {
         s.draw();
     }
 }

 class Shape {
     abstract void draw();
 }

 class Rectangle extends Shape  {
     public void draw() {
         // draw the rectangle
     }
 } 


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow