open closed principle example kotlin

Open-Closed Principle in Kotlin: Coding Java Examples

By Robert Rodriguez
AD

In the realm of object-oriented programming, the Open-Closed Principle (OCP) is a fundamental tenet that dictates software entities should be open for extension, but closed for modification. This principle is particularly relevant in the Kotlin programming language, where its powerful features enable easy extension of classes without changing their source code. Let's delve into this principle and explore some practical Kotlin examples.

Kotlin's flexibility and expressiveness make it an excellent choice for implementing the Open-Closed Principle. This is due to its support for abstract classes, interfaces, and extension functions, which allow us to modify the behavior of existing classes without altering their source code.

Extensions and Interfaces in Kotlin

Kotlin's extension functions enable us to add new functionality to existing classes without modifying their source code. This is a testament to the Open-Closed Principle, as it allows us to extend a class's behavior without modifying its closed, internal structure.

AD
open×close
open×close
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

Interfaces play a crucial role in OCP implementation, as they allow us to define a contract that can be implemented by existing or new classes. This promotes extensibility without modification, as we can create new implementations without altering the original class.

Extension Functions

Extension functions allow us to add new functionality to existing classes, enabling us to follow OCP. Suppose we have a `Person` class and we want to add a new method `greet` without modifying its source code:

Verb : ( close ) .
Verb : ( close ) .
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
Kotlin cheat sheet 3
Kotlin cheat sheet 3
```kotlin fun Person.greet() = println("Hello, I'm ${this.name}!") ```

We can now use this extension function with any existing `Person` instance, following OCP:

```kotlin val person = Person("Alice") person.greet() // prints: Hello, I'm Alice! ```

Interfaces

Implementing new classes that adhere to existing interfaces allows us to extend functionality without modifying the original class. Let's consider a simple example with a `Logger` interface:

AD
```kotlin interface Logger { fun log(message: String) } class ConsoleLogger : Logger { override fun log(message: String) = println(message) } ```

We can now create new `Logger` implementations without altering the `ConsoleLogger` class. This adheres to the Open-Closed Principle, as we are extending the behavior without modifying the existing code.

List methods in Kotlin
List methods in Kotlin
New ideas open new doors 🚪 Creative Thinking Inspiration, Inspirational Quote Art, Minimalist Black And Yellow Design, Motivational Wall Art Ideas, Staircase With Glowing Light, 2d Motion Graphics, Animated Door Opening, Door Opening Animation, Door Reveal
New ideas open new doors 🚪 Creative Thinking Inspiration, Inspirational Quote Art, Minimalist Black And Yellow Design, Motivational Wall Art Ideas, Staircase With Glowing Light, 2d Motion Graphics, Animated Door Opening, Door Opening Animation, Door Reveal
an open door with the words closing doors and opening new ones above it is a drawing of a man standing in front of two open doors
an open door with the words closing doors and opening new ones above it is a drawing of a man standing in front of two open doors
Open Close
Open Close
Open and closed signs. Vector illustration.
Open and closed signs. Vector illustration.
TIL 020 – open(0)
TIL 020 – open(0)

The Strategy Pattern in Kotlin

The Strategy Pattern is a great way to exemplify the OCP. It lets us choose an algorithm at runtime to perform an operation, enabling us to add new algorithms without changing the original code.

The Strategy Pattern has three key components: the `Strategy` interface, the concrete `Strategy` classes, and the `Context` class that uses these strategies:

AD
```kotlin interface PaymentStrategy { fun pay(amount: Double) } class PayPalStrategy : PaymentStrategy { override fun pay(amount: Double) { /* Implement PayPal payment */ } } class CreditCardStrategy : PaymentStrategy { override fun pay(amount: Double) { /* Implement credit card payment */ } } class ShoppingCart { private lateinit var strategy: PaymentStrategy fun setStrategy(strategy: PaymentStrategy) { this.strategy = strategy } fun pay(amount: Double) = strategy.pay(amount) } ```

With this approach, we can add new payment strategies (e.g., `BitcoinStrategy`) without modifying the `ShoppingCart` class. This adherence to the Open-Closed Principle promotes extensibility and maintainability in our Kotlin codebase.

Getting started with Kotlin Multiplatform Part - 1: Working with Mobile Platforms
Getting started with Kotlin Multiplatform Part - 1: Working with Mobile Platforms
keep door closed icon on white background. keep door closed symbol. flat style.
keep door closed icon on white background. keep door closed symbol. flat style.
Start Learning Kotlin For Free
Start Learning Kotlin For Free
an orange and white poster with instructions on how to use the font in different languages
an orange and white poster with instructions on how to use the font in different languages
KOTLIN VS REACT NATIVE
KOTLIN VS REACT NATIVE
SOLID Principles In C# - Single Responsibility Principle
SOLID Principles In C# - Single Responsibility Principle
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
an open / closed sign with the words pringle ocf
an open / closed sign with the words pringle ocf
Liskov Substitution Principal explained with examples in Java
Liskov Substitution Principal explained with examples in Java
5 Surprisingly Clever Design Choices You Never Noticed
5 Surprisingly Clever Design Choices You Never Noticed
adjetivo oposto antônimo palavras em inglês abrir ilustração fechada para crianças explicação flashcard com rótulo de texto
adjetivo oposto antônimo palavras em inglês abrir ilustração fechada para crianças explicação flashcard com rótulo de texto
the words closure are written in black and white, with arrows pointing to different directions
the words closure are written in black and white, with arrows pointing to different directions
6. The Android Lifecycle | Android Programming with Kotlin for Beginners
6. The Android Lifecycle | Android Programming with Kotlin for Beginners

In the world of software development, the Open-Closed Principle is a guiding light that leads us towards creating more maintainable, extensible, and flexible code. By leveraging Kotlin's powerful features such as extension functions and interfaces, we can effectively follow this principle and create code that is open for extension but closed for modification. Embrace the power of Kotlin and strive to build better, more resilient software architectures.

AD