◆Smart Home Ideas Journal

Open-Closed Principle: Java Code Examples

By

In the realm of software design principles, the Open-Closed Principle (OCP) stands as a cornerstone, promoting agility and maintainability. Introduced by Bertrand Meyer in 1995 and later refined by Robert C. Martin, this principle advocates for modules to be open for extension but closed for modification. In other words, code should be designed in such a way that new functionality can be added without altering existing code, ensuring a stable and secure system. Let's delve into the Open-Closed Principle, exploring its relevance and providing practical examples to illustrate its application.

The Open-Closed Principle serves two primary objectives. First, it makes the software more stable and secure by minimizing the risk of introducing bugs when adding new features. Second, it enhances maintainability by reducing the need to refactor and touch existing code, thus saving time and resources. By adhering to OCP, developers can focus on extending the system's behavior, rather than modifying its structure.

Understanding the Open-Closed Principle

The Open-Closed Principle encourages the use of abstraction to create modules that can be extended without being modified. Here, ' Modules' refer to functions, classes, or packages within a software system. These modules should be designed to accept new behaviors without altering their existing code. This is typically achieved through the use of interfaces, inheritance, and composition.

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
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+

To further illustrate the Open-Closed Principle, let's consider a simple example of a logging system. Without adhering to OCP, we might have a monolithic logger with multiple logging levels (DEBUG, INFO, WARNING, ERROR). Adding a new logging level would require modifying the existing logger's code, violating the Open-Closed Principle. Now, let's see how we can restructure this system to comply with OCP.

Refactoring for Open-Closed Principle Compliance

To conform with the Open-Closed Principle, we can introduce a logging interface with methods for each logging level. Each method will accept a string message as a parameter. This interface allows us to add new logging levels without modifying the existing codebase. Here's a simple implementation in Java:

open×close
open×close
the instructions for how to use an open canister
the instructions for how to use an open canister
Open-close
Open-close

public interface Logger {
    void logDebug(String message);
    void logInfo(String message);
    void logWarning(String message);
    void logError(String message);
}

With this interface in place, we can implement concrete logger classes that extend functionality without modifying the original Logger interface. For instance, we can create a FileLogger that logs messages to a file or a ConsoleLogger that logs messages to the console. This approach allows us to easily add new logging mechanisms without changing the existing code.

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 Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
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
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

Practical Examples of the Open-Closed Principle

The Open-Closed Principle can be applied in various scenarios. Let's explore two more practical examples:

1. Strategy Pattern with OCP
The Strategy Pattern, a behavioral design pattern, defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime. By applying the Open-Closed Principle, we can add new algorithms to this pattern without modifying the existing code. In this way, the Strategy Pattern remains open for extension (add new strategies) but closed for modification.

2. Dependency Injection with OCP
Dependency Injection (DI) is a technique to achieve Inversion of Control (IoC) between objects. To maintain OCP, DI containers should be designed to allow new services to be injected without altering the existing codebase. This can be achieved by defining interfaces for the services and injecting implementations through these interfaces.

OPEN VS CLOSED? WHICH MINDSET DO YOU HAVE?
OPEN VS CLOSED? WHICH MINDSET DO YOU HAVE?
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
Space Planning Basics - introduction for architectural design
Space Planning Basics - introduction for architectural design
Teaching & Learning
Teaching & Learning
two signs showing how to open and close clothes
two signs showing how to open and close clothes
Body language
Body language
Object-Oriented Software Principles
Object-Oriented Software Principles
Open and closed signs | Free Vector
Open and closed signs | Free Vector
Open and Close Posts for Shop Graphic by Yapivector · Creative Fabrica
Open and Close Posts for Shop Graphic by Yapivector · Creative Fabrica
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
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
SOLID Principles Explained: A Visual Guide to Better System Design
SOLID Principles Explained: A Visual Guide to Better System Design

The Role of Abstraction in the Open-Closed Principle

Abstraction plays a crucial role in the Open-Closed Principle, as it helps define the points of extensibility in a system. By using interfaces, abstract classes, or other forms of abstractions, we can create modules that can be extended by implementing the defined abstractions. This approach allows new functionality to be added without modifying the original code.

Abstraction also enables better adherence to the Single Responsibility Principle (SRP), which promotes a module's code to have only one reason to change. By combining OCP and SRP, we can create a more modular, stable, and maintainable codebase.

Finally, it is essential to remember that while the Open-Closed Principle encourages minimizing code modifications, it does not eliminate the need for refactoring entirely. Code may still need to be refactored to improve readability, remove duplication, or address performance issues. However, by adhering to the Open-Closed Principle, we can greatly reduce the risk of introducing new bugs and increase the stability and maintainability of our codebase. As software engineers, it's our responsibility to strive for a balance between adherence to design principles and the practical realities of maintaining and evolving complex systems.