Sök…


Introduktion

I Open Close-principen anges att utformningen och skrivningen av koden ska göras på ett sätt att ny funktionalitet ska läggas till med minimiförändringar i den befintliga koden. Designen bör göras på ett sätt som gör det möjligt att lägga till ny funktionalitet som nya klasser och hålla så mycket som möjligt befintlig kod oförändrad. Programvaruenheter som klasser, moduler och funktioner bör vara öppna för förlängning men stängda för ändringar.

Anmärkningar

Liksom varje princip är Open Close Principle bara en princip. Att göra en flexibel design innebär extra tid och ansträngning som läggs på den och det introducerar en ny nivå av abstraktion som ökar kodens komplexitet. Så denna princip bör tillämpas inom det område som troligen kommer att ändras. Det finns många designmönster som hjälper oss att utöka koden utan att ändra den, till exempel dekoratör.

Öppna Stäng principöverträdelse

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

Öppna Stäng principstöd

/*
* 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
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow