Open-Closed Principle (OCP)

The Open-Closed Principle (OCP) is the second pillar of SOLID design after the Single Responsibility Principle (SRP) and emphasizes the importance of making your code open for extension while being closed for modification. This principle encourages developers to design software modules that can be extended or enhanced without altering their existing source code. By doing so, you ensure that changes to your codebase won’t inadvertently introduce bugs in previously working components.

Let’s revisit our FileManager example to see how OCP comes into play. Imagine that, in addition to reading and writing files, you now need to support zipping and unzipping files. In a non-OCP-compliant system, you might be tempted to modify the FileManager class to accommodate this new functionality:

class FileManager
{
    public function readFile($filePath)
    {
        // Read file content
    }

    public function writeToFile($filePath, $data)
    {
        // Write data to the file
    }

    // New method added for zipping files
    public function zipFile($filePath)
    {
        // Zip the file
    }

    // New method added for unzipping files
    public function unzipFile($filePath)
    {
        // Unzip the file
    }
}

While this approach appears convenient, it violates OCP because it requires modifying the existing FileManager class, which can introduce unexpected issues in your codebase. Instead, we can make use of the OCP by creating separate classes to handle file zipping and unzipping, extending the functionality without changing the existing code:

class FileManager
{
    public function readFile($filePath)
    {
        // Read file content
    }

    public function writeToFile($filePath, $data)
    {
        // Write data to the file
    }
}

class Zipper
{
    public function zipFile($filePath)
    {
        // Zip the file
    }

    public function unzipFile($filePath)
    {
        // Unzip the file
    }
}

By introducing the Zipper class, we adhere to OCP, which:

  1. allows us to add new features without touching the existing codebase,
  2. makes code more reusable (it’s more probable that someone will use the Zipper when faced with the task of zipping and unzipping files),
  3. makes our code more resilient to change and easier to maintain over time.

The Open-Closed Principle encourages developers to think ahead and design their software modules in a way that facilitates extensibility, promoting cleaner, more robust code. Another one worth checking is the Liskov Substitution Principle (LSP).

Leave a Comment