The Open/Closed Principle: A Door That Never Shuts, A Room That Always Grows
In the ever-shifting architecture of software design, one rule whispers louder than the rest: “Open for extension, closed for modification.” This is the Open/Closed Principle (OCP), a cornerstone of SOLID, a path to designs that endure the chaos of constant change.
The Perils of Modifying the Past
Picture it: a class designed long ago, a proud construct of methods and logic, its purpose clear. But time passes, requirements shift, and now—your old class must change. Each modification stirs the ghosts of prior logic, introducing new risks, new bugs, unraveling the careful tapestry of what once worked. The past grows fragile, and your class becomes a liability.
Extending the Future Without Breaking the Past
OCP urges you to stop rewriting the past. Instead, extend functionality through abstraction, interfaces, and inheritance. Let your class remain stable—a foundation upon which new features stand tall, untouched by the shifting winds of requirements.
Example: Open/Closed in Action
public abstract class Notification
{
public abstract void Send(string message);
}
public class EmailNotification : Notification
{
public override void Send(string message)
{
Console.WriteLine($"Email sent: {message}");
}
}
public class SmsNotification : Notification
{
public override void Send(string message)
{
Console.WriteLine($"SMS sent: {message}");
}
}
public class NotificationService
{
private readonly List<Notification> _notifications = new List<Notification>();
public void AddNotification(Notification notification)
{
_notifications.Add(notification);
}
public void NotifyAll(string message)
{
foreach (var notification in _notifications)
{
notification.Send(message);
}
}
}
What Changed?
Instead of altering existing code to add new notification types (like Slack or Push), we extend by adding new classes. Email and SMS are stable, untouched—open for new features but closed to risky modifications.
Takeaway
The Open/Closed Principle is a design philosophy that respects the stability of the past while embracing the inevitability of future growth. Build your classes to extend without fear of breaking what’s already there.
Stay tuned as we continue our journey through SOLID’s winding corridors.
#writtenfrommyphone
#latenightthoughts
Principal Engineer @Atlassian | Empowering Senior Engineers to Transition into Leadership roles by focussing on Foundational Principles of System Design and Leadership | NIT Bhopal
3moI’ll Argue, Step 1: Identity the bottleneck