open-closed principle example

Open-Closed Principle: Essential Coding Examples

By Michael Brown
AD

The Open-Closed Principle (OCP) is a fundamental object-oriented design concept that advocates for software entities, namely classes, modules, and functions, to be open for extension but closed for modification. This means that you should be able to extend a class's functionality, without modifying its source code. It's one of the five SOLID principles, providing a roadmap for writing more stable, maintainable, and easily testable code.

To illustrate OCP, consider a logging system that supports logging to the console and a file. Following the OCP, you wouldn't modify the existing Logger class to add new log destinations. Instead, you'd extend the Logger's functionality to include new loggers.

Open for Extension: Abstract Logger Example

The following Java example shows a Logger class that is open for extension. It uses the Strategy Pattern, making use of abstract classes and interfaces to fulfill the OCP.

AD
Open and close worksheet | Learning Opposites | for kids
Open and close worksheet | Learning Opposites | for kids
Open and Closed Class Words in English | Definition | Examples | Differences
Open and Closed Class Words in English | Definition | Examples | Differences
open×close
open×close

The Logger class accepts an AbstractLoggerStrategy, allowing it to support any new logging strategy that extends AbstractLoggerStrategy.

AbstractLoggerFactory Class

The AbstractLoggerFactory class is responsible for creating logger instances.

SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
Open-close
Open-close

Here's a simple implementation:

public abstract class AbstractLoggerFactory {

  public static AbstractLoggerStrategy getLogger(String type) {
    if ("console".equals(type)) {
      return new ConsoleLoggerStrategy();
    } else if ("file".equals(type)) {
      return new FileLoggerStrategy();
    } else {
      throw new IllegalArgumentException("Unknown logger type: " + type);
    }
  }
}

Logger Class

The Logger class uses the strategy to log messages.

Here's a simple implementation:

public class Logger {
  private AbstractLoggerStrategy strategy;

  public Logger(AbstractLoggerStrategy strategy) {
    this.strategy = strategy;
  }

  public void log(String message) {
    strategy.log(message);
  }
}

Open for Extension: Bean Configuration Example

In Spring Framework, you can also apply OCP in bean configuration. You can design your application to allow beans to be extended without modification, using, for instance, XML configuration.

Instead of hard-coding beans in the XML configuration, you can create extension points, allowing additional beans to be easily added.

spring-config.xml

Here's a simple Spring XML configuration:

The LoggerFactory bean allows new loggers to be added by simply including a new bean configuration in another XML file.


spring-extensions.xml

Here's an extension configuration file:

New loggers can be added by including this file in the main configuration:


By following the OCP, you've made your system more flexible and easier to extend. You've decoupled the main application from new loggers that can be loaded dynamically. This supports the long-term maintainability of your codebase and makes it easier to add new features without modifying existing classes.

four different pictures with the words open, closed, and in front of an open door
four different pictures with the words open, closed, and in front of an open door
the instructions for how to use an open canister
the instructions for how to use an open canister
Open vs Closed Cooling System (Differences Explained Simply)
Open vs Closed Cooling System (Differences Explained Simply)
Open Mind vs Closed Mind | Powerful Life Lesson Illustration
Open Mind vs Closed Mind | Powerful Life Lesson Illustration
two stickers with the words sorry we're closed and an open sign that says sorry
two stickers with the words sorry we're closed and an open sign that says sorry
Open close
Open close
Nikki Siapno on LinkedIn: SOLID principles explained in under 2 minutes: Whether or not you use… ...
Nikki Siapno on LinkedIn: SOLID principles explained in under 2 minutes: Whether or not you use… ...
two buckets with water coming out of them and the words, what are you? open - minded closed - minded
two buckets with water coming out of them and the words, what are you? open - minded closed - minded
Open and closed signs | Free Vector
Open and closed signs | Free Vector
an open and closed umbrella next to two small houses with the words open close above them
an open and closed umbrella next to two small houses with the words open close above them
Teaching & Learning
Teaching & Learning
Object-Oriented Software Principles
Object-Oriented Software Principles
Open and Close Posts for Shop Graphic by Yapivector · Creative Fabrica
Open and Close Posts for Shop Graphic by Yapivector · Creative Fabrica
two signs showing how to open and close clothes
two signs showing how to open and close clothes
three open boxes with the words closed, closed and opened in orange letters on them
three open boxes with the words closed, closed and opened in orange letters on them
Space Planning Basics - introduction for architectural design
Space Planning Basics - introduction for architectural design
Unlock Your Potential: Open vs. Closed Mindset 🧠🔓
Unlock Your Potential: Open vs. Closed Mindset 🧠🔓
Open and Close, Pre-Number Concept for Kindergarten, Concept of Open and Close, Opposites-Open/Close
Open and Close, Pre-Number Concept for Kindergarten, Concept of Open and Close, Opposites-Open/Close
a drawing of a woman with her arms outstretched and the words open closed above her head
a drawing of a woman with her arms outstretched and the words open closed above her head
AD