Zoeken…


Invoering

Het Open Close Principle stelt dat het ontwerp en schrijven van de code moet worden gedaan op een manier dat nieuwe functionaliteit moet worden toegevoegd met minimale wijzigingen in de bestaande code. Het ontwerp moet zo worden uitgevoerd dat nieuwe functionaliteit als nieuwe klassen kan worden toegevoegd, waarbij bestaande code zoveel mogelijk ongewijzigd moet blijven. Software-entiteiten zoals klassen, modules en functies moeten open staan voor uitbreiding maar gesloten voor wijzigingen.

Opmerkingen

Zoals elk principe is Open Close Principle slechts een principe. Het maken van een flexibel ontwerp vereist extra tijd en moeite en het introduceert een nieuw abstractieniveau dat de complexiteit van de code verhoogt. Dit principe moet dus worden toegepast op die gebieden die het meest waarschijnlijk zullen worden gewijzigd. Er zijn veel ontwerppatronen die ons helpen code uit te breiden zonder deze te wijzigen, bijvoorbeeld decorateur.

Open Sluiten Principe schending

/* 
* 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 Sluiten Principe-ondersteuning

/*
* 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
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow