Open/Closed Principle
noun
say it: “OH-pun KLOHZD PRIN-suh-pul” /ˈoʊpən kloʊzd ˈprɪnsəpəl/
The principle that working code should be closed to edits and open to additions: new behavior arrives as new code.
What is Open/Closed Principle?
The Open/Closed Principle says code should be open for extension but closed for modification: you add new behavior by adding new classes, not by editing working ones.
public interface IDiscount { decimal Apply(decimal price); }
// New discount? Add a class; the checkout code stays untouched.
public class StudentDiscount : IDiscount
{
public decimal Apply(decimal price) => price * 0.9m;
}
In a sentence
- “Thanks to the open/closed principle, the middle school's 4-point scale was a new class, and the grade code wasn't touched.”
Level: Freelancer · More OOP terms at this level
Updated