S[O]LID: The Open-Closed Principle

Open for Extension; Closed for Modification

Posted on 07/16/2021 by Kasey Wahl
...

Dear Coder,

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."

Great. 

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.

Clickity Clacks,

Kasey



0 Comment(s)
Login to add a comment
Search
About Kasey
I love to make cool things with great people.

Let's grab a coffee and chat! (in person or on Zoom).

Connect with me on Github, LinkedIn, Twitter, or my personal website, kaseywahl.io.