Open-Closed Principle (OCP) in .NET 6 Core

Introduction

As a beginner developer, you're likely on a quest to create clean, maintainable, and scalable code. One of the guiding principles in this journey is the "Open-Closed Principle" from the SOLID principles. In this article, we'll break down the Open-Closed Principle and explain it in a beginner-friendly way using a simple .NET 6 Core example.

What is the Open-Closed Principle (OCP)?

The Open-Closed Principle (OCP) is the second letter in SOLID, and it encourages you to design software components that are open for extension but closed for modification. In simpler terms, it means that your code should be adaptable to new features or requirements without changing the existing codebase. You can add new functionality without altering the existing, working code.

Imagine you have a toolbox with various tools. When you need a new tool, you don't modify the existing ones; instead, you add a new tool to your collection. This is the essence of the Open-Closed Principle – your code should be open for extension, just like your toolbox.

Why is OCP Important?

  1. Maintenance: It reduces the risk of introducing bugs when you add new features. Your existing, working code remains untouched.

  2. Scalability: Your codebase can grow without the fear of breaking existing functionality.

  3. Collaboration: Different team members can work on extending the system without interfering with each other's code.

A Simple .NET 6 Core Example

Let's dive into a straightforward .NET 6 Core example to understand OCP better. We'll build upon the Book and Reservation classes used in our previous article on the Single Responsibility Principle (SRP).

 If you haven't read it yet, you can check it out  https://www.c-sharpcorner.com/article/single-responsibility-principle-srp-in-net-core/.

Original Book Class

Here's the original Book class, which represents book data:

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string ISBN { get; set; }

    public Book(string title, string author, string isbn)
    {
        Title = title;
        Author = author;
        ISBN = isbn;
    }
}

Extending the Reservation Class

Now, let's extend the Reservation class without m odifying the existing code. We'll add a new feature to calculate a discount for library members:

public class Reservation
{
    public Book Book { get; set; }
    public string User { get; set; }
    public DateTime DueDate { get; set; }

    public Reservation(Book book, string user, DateTime dueDate)
    {
        Book = book;
        User = user;
        DueDate = dueDate;
    }

    public decimal CalculateLateFee()
    {
        // Calculate late fee logic here
        // For example, you could calculate the late fee based on the due date.
        TimeSpan overdue = DateTime.Now - DueDate;
        if (overdue.TotalDays > 0)
        {
            decimal lateFee = overdue.TotalDays * 2.0M; // $2 per day late fee
            return lateFee;
        }
        return 0; // No late fee if not overdue
    }

    public decimal CalculateMemberDiscount()
    {
        // Calculate the member discount logic here
        // For example, library members get a 10% discount on late fees.
        decimal lateFee = CalculateLateFee();
        return lateFee * 0.10M;
    }
}

In this example, we extended the Reservation class by adding a new method, CalculateMemberDiscount, to calculate a discount for library members. We did this without modifying the existing code, such as the Book or CalculateLateFee method.

This adheres to the Open-Closed Principle because we extended the class's functionality without changing its original code. Our code is open for extension, closed for modification, just like adding a new tool to your toolbox without altering the existing ones.

Conclusion

The Open-Closed Principle encourages you to design code that can be extended for new features without changing the existing, working code. This principle is vital for maintaining, scaling, and collaborating on software projects.

In our .NET 6 Core example, we saw how you can extend a class's functionality without altering the existing codebase, thus following the Open-Closed Principle. As a beginner developer, embracing OCP will help you create more robust and adaptable software. Keep building, keep learning, and keep coding!

Explore the Single Responsibility Principle (SRP) in .NET Core through this informative article.  Read the full article on Single Responsibility Principle (SRP) in .NET Core

😊Please consider liking and following me for more articles and if you find this content helpful.👍


Similar Articles
Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.