Earlier this week, I wrote to you about the Single Responsibility Principle of software design and how it is the "S" in the acronym, "SOLID."
Today I'm continuing the thought and writing about "O": the Open-Closed principle.
The pared-down explanation is that software should be "open for extension, but closed for modification."
But what does that mean, exactly?
Let's look at an example built into Microsoft's Identity Framework.
Microsoft's IdentityUser class contains a set of properties for a User out of the box:
These properties are "closed for modification." They're built into Identity Framework, but cannot and should not be manipulated by developers.
But what if I want the users of my application to have properties beyond IdentityUser?
I can extend the IdentityUser class that inherits from IdentityUser with the properties I need in my application.
My BTUser class inherits all of the properties from IdentityUser, but also extends it to include properties more specific to the needs of my application.
Fundamentally, the idea behind the Open-Closed principle is that, to preserve code over time as new developers work on the project and as the code base grows, it is better to change software by creating new code or functionality instead of changing existing code.
This is important because creating separate classes also isolates risks associated with changes, which means new code is easier to test and manage.
Note, dearest Coder, that the first two SOLID principles that I've written about complement each other.
The Single Responsibility Principle says that a class should only have one purpose.
The Open-Closed Principle says that classes should be open for extension and closed for modification.
Considered together, classes that have one responsibility have a clearly-defined purpose, and a single purpose is generally easier to extend and manage through inheritance than a class that has too many reasons to change.
I hope you're finding this analysis of the SOLID principles useful, dearest Coder.
Until next time, godspeed in your keystrokes.