Suche…


Einführung

Das Open-Close-Prinzip besagt, dass das Design und Schreiben des Codes so erfolgen sollte, dass neue Funktionen mit minimalen Änderungen im vorhandenen Code hinzugefügt werden. Das Design sollte so gestaltet werden, dass neue Funktionen als neue Klassen hinzugefügt werden können, wobei der vorhandene Code so weit wie möglich unverändert bleibt. Software-Entitäten wie Klassen, Module und Funktionen sollten für die Erweiterung geöffnet, für Änderungen jedoch geschlossen sein.

Bemerkungen

Wie jedes Prinzip ist das Open-Close-Prinzip nur ein Prinzip. Das Erstellen eines flexiblen Designs erfordert zusätzlichen Zeit- und Arbeitsaufwand und führt zu einer neuen Abstraktionsebene, wodurch der Code komplexer wird. Daher sollte dieser Grundsatz in den Bereichen angewendet werden, die am wahrscheinlichsten geändert werden. Es gibt viele Designmuster, die uns dabei helfen, Code zu erweitern, ohne ihn zu ändern, beispielsweise Dekorateur.

Open Close Prinzipverletzung

/* 
* 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;
     }
 }

Open Close Principle-Unterstützung

/*
* 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
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow