OCP: Open/Closed Principle in Swift (with code examples) — SOLID Principles

Gizem Türker
4 min readJun 24, 2022

--

A software artifact — such as a class or a component — should be open for extension but closed for modification.

A Module should be open for extension but closed for modification.[1]

In the realm of software development, the Open/Closed Principle (OCP) stands as a beacon of modular and resilient design, guiding developers towards creating systems that are both robust against changes and adaptable to new functionalities. This principle, a critical aspect of the SOLID acronym, encourages the design of software entities such as classes, modules, and functions to be open for extension but closed for modification. The elegance of OCP lies in its simplicity and the profound impact it has on the lifecycle of software development, fostering environments where innovation and stability coexist harmoniously.

OCP says: These components, which we have listed from private to general, should be open to expansion and closed to change.

· Methods

· Classes

· Packages

· Modules

· Systems

The Essence of OCP in Modern Development

OCP transcends the boundaries of mere coding practices to embody a philosophy that champions forward-thinking and flexibility in software design. It addresses a fundamental dilemma in software engineering: how to add new features without risking the integrity of existing functionality. By adhering to OCP, developers can extend a system’s behavior without modifying its source code, effectively decoupling the evolution of a system from its historical complexities.

A Deeper Dive into OCP with Swift Examples

To illustrate the concept of OCP, let’s consider a real-world scenario in the Swift programming language, focusing on a feature-rich application that requires dynamic user profiles with multiple address types.

Scenario Before OCP: The Brittle Foundation

Initially, our application might feature a simplistic User class incorporating a singular Address type. This design, while straightforward, quickly becomes a liability as the application grows to accommodate diverse user needs, including billing, shipping, and contact addresses.

class Address {
var street: String
var city: String
// Initial simplistic address model
}

class User {
var name: String
var address: Address
// Tightly coupled user and address relationship
}

In this architecture, introducing a new address type necessitates invasive changes to the User class, violating OCP by modifying existing code, thereby increasing the risk of bugs and regression.

Embracing OCP: A Flexible and Scalable Approach

Transitioning to an OCP-compliant design involves abstracting address types behind an AddressProtocol, which serves as a contract for any address type. This abstraction allows the User class to interact with an array of addresses, each conforming to the AddressProtocol, without concern for their concrete implementations.

protocol AddressProtocol {
var street: String { get }
var city: String { get }
// Address behavior contract
}

class BillingAddress: AddressProtocol {
var street: String
var city: String
// Specific implementation for a billing address
}

class ShippingAddress: AddressProtocol {
var street: String
var city: String
// Specific implementation for a shipping address
}

class User {
var name: String
var addresses: [AddressProtocol]
// Flexibly holds multiple address types
}

This approach not only aligns with OCP but significantly enhances the application’s adaptability, allowing for the seamless introduction of new address types without revisiting or revising the User class.

Beyond Code: OCP as a Catalyst for Innovation and User Satisfaction

The strategic adoption of OCP transcends technical benefits, fostering a development culture that is agile, user-centric, and innovation-friendly. By liberating the codebase from the constraints of frequent modifications, OCP empowers developers to focus on creating value through new features and functionalities, directly translating to improved user experiences and satisfaction. Applications evolve in a controlled manner, with new capabilities introduced without disrupting existing services, ensuring a stable and reliable user experience.

Moreover, OCP-driven designs facilitate a modular architecture that simplifies testing, enhances maintainability, and promotes reusability, further contributing to the overall quality and longevity of the software product. These characteristics are invaluable in today’s fast-paced, user-expectation-driven market, where the ability to rapidly adapt and innovate without sacrificing quality or performance can significantly differentiate and elevate a software product.

The Transformative Power of OCP

In conclusion, the Open/Closed Principle is not merely a guideline but a transformative paradigm that redefines how software is developed, maintained, and evolved. By embracing OCP, developers and organizations can create systems that are resilient, adaptable, and poised for future growth, all while maintaining a steadfast focus on quality and user experience. As we continue to explore the depths of SOLID principles and their practical applications, particularly in Swift, it becomes increasingly clear that these principles are foundational to crafting exceptional software that stands the test of time and technology shifts.

Embarking on this journey through the SOLID principles, with OCP as a critical milestone, illuminates the path toward software excellence. It’s a testament to the enduring relevance of these principles in shaping the future of software development, a future where adaptability, reliability, and user satisfaction converge to define success.

Stay engaged, stay curious, and let’s continue to elevate our craft to new heights. For more insights and discussions, follow along LinkedIn, Twitter, and Github and join the conversation in advancing the art and science of software development.

This was the second article of the series of five about SOLID and its use in Swift. I hope you have enjoyed it. For the first article check the link.

Discuss in the comment.

What is the SOLID Principle?

SRP: Single Responsibility Principle in Swift (with code examples) — SOLID Principles

OCP: Open/Closed Principle in Swift (with code examples) — SOLID Principles

LSP: Liskov Substitution Principle in Swift (with code examples) — SOLID Principles

Interface Segregation Principle in Swift (with code examples) — SOLID Principles

Useful links:

  1. https://blog.cleancoder.com/
  2. https://pyartez.github.io/architecture/solid-principles-in-swift-open-closed-principle.html
  3. https://medium.com/movile-tech/open-closed-principle-in-swift-6d666270953d
  4. https://www.scaledrone.com/blog/solid-principles-for-becoming-a-better-ios-swift-developer/

--

--

Gizem Türker

🚀 Crafting apps & leading the charge in tech as an iOS Developer, Entrepreneur & Solopreuner. Ex- @PeltonTechnology founder.