เอนทิตีซอฟต์แวร์ เช่น คลาส โมดูล และฟังก์ชัน ควรเปิดเพื่อขยายแต่ปิดเพื่อแก้ไข
คำจำกัดความ − Open Close Principle ระบุว่าการออกแบบและการเขียนโค้ดควรทำในลักษณะที่ควรเพิ่มฟังก์ชันการทำงานใหม่โดยมีการเปลี่ยนแปลงขั้นต่ำในโค้ดที่มีอยู่ การออกแบบควรทำในลักษณะที่อนุญาตให้มีการเพิ่มฟังก์ชันการทำงานใหม่เป็นคลาสใหม่ โดยรักษาโค้ดที่มีอยู่ให้มากที่สุดเท่าที่เป็นไปได้ไม่เปลี่ยนแปลง
ตัวอย่าง
รหัสก่อนเปิดหลักการปิด
using System;
using System.Net.Mail;
namespace SolidPrinciples.Open.Closed.Principle.Before{
public class Rectangle{
public int Width { get; set; }
public int Height { get; set; }
}
public class CombinedAreaCalculator{
public double Area (object[] shapes){
double area = 0;
foreach (var shape in shapes){
if(shape is Rectangle){
Rectangle rectangle = (Rectangle)shape;
area += rectangle.Width * rectangle.Height;
}
}
return area;
}
}
public class Circle{
public double Radius { get; set; }
}
public class CombinedAreaCalculatorChange{
public double Area(object[] shapes){
double area = 0;
foreach (var shape in shapes){
if (shape is Rectangle){
Rectangle rectangle = (Rectangle)shape;
area += rectangle.Width * rectangle.Height;
}
if (shape is Circle){
Circle circle = (Circle)shape;
area += (circle.Radius * circle.Radius) * Math.PI;
}
}
return area;
}
}
} โค้ดหลังเปิดหลักการ
namespace SolidPrinciples.Open.Closed.Principle.After{
public abstract class Shape{
public abstract double Area();
}
public class Rectangle: Shape{
public int Width { get; set; }
public int Height { get; set; }
public override double Area(){
return Width * Height;
}
}
public class Circle : Shape{
public double Radius { get; set; }
public override double Area(){
return Radius * Radius * Math.PI;
}
}
public class CombinedAreaCalculator{
public double Area (Shape[] shapes){
double area = 0;
foreach (var shape in shapes){
area += shape.Area();
}
return area;
}
}
}