Ricerca…


introduzione

L'Open Close Principle afferma che la progettazione e la scrittura del codice dovrebbero essere fatte in modo tale da aggiungere nuove funzionalità con modifiche minime nel codice esistente. Il design dovrebbe essere fatto in modo da consentire l'aggiunta di nuove funzionalità come nuove classi, mantenendo il più possibile il codice esistente invariato. Le entità software come classi, moduli e funzioni dovrebbero essere aperte per estensione ma chiuse per modifiche.

Osservazioni

Come ogni principio Open Close Principle è solo un principio. Realizzare un design flessibile richiede tempo e sforzi aggiuntivi per esso e introduce un nuovo livello di astrazione che aumenta la complessità del codice. Quindi questo principio dovrebbe essere applicato in quelle aree che sono più suscettibili di essere modificate. Esistono molti modelli di progettazione che ci aiutano ad estendere il codice senza cambiarlo, ad esempio il decoratore.

Apri la violazione del principio di chiusura

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

Apri il supporto del principio di chiusura

/*
* 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
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow