open closed principle typescript

Mastering the Open-Closed Principle with TypeScript

By Rachel Harris
AD

In the realm of object-oriented programming, the Open-Closed Principle (OCP) is a fundamental concept that promotes software extensibility and maintainability. This principle, outlined in SOLID principles by Robert C. Martin, suggests that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. Now, let's explore how we can apply this principle in TypeScript, making our code more flexible and easier to manage.

Before diving into OCP in TypeScript, let's understand its benefits. Adhering to this principle offers several advantages, including reduced complexity, improved maintainability, and enhanced flexibility. It lets you extend the behavior of a system without modifying its source code, which is particularly beneficial in cases where you're dealing with third-party libraries or legacy code.

Understanding Open for Extension

The 'Open for Extension' part of OCP means that we should design our modules or classes in such a way that they can be extended or adapted to new requirements without modification. In TypeScript, this can be achieved using various features like interfaces, classes, and extension methods.

AD
Explained: OPEN/CLOSE Principle In 2 Minutes
Explained: OPEN/CLOSE Principle In 2 Minutes
25 TYPESCRIPT TRICKS EVERY DEVELOPER SHOULD KNOW
25 TYPESCRIPT TRICKS EVERY DEVELOPER SHOULD KNOW
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+
SOLID: Part 2 - The Open/Closed Principle | Envato Tuts+

A practical way to achieve this is by using interfaces to define contracts for our code. This allows us to extend functionality by implementing these interfaces without touching the original code. Let's illustrate this with an example.

Using Interfaces for Extension

Let's consider a simple logger interface:

typescript basic
typescript basic
10 Clean Code Principles for Writing Better TypeScript
10 Clean Code Principles for Writing Better TypeScript
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
```typescript interface Logger { log(message: string): void; } ```

Implementing new loggers, like a console logger, can be done without modifying the original logger interface:

```typescript class ConsoleLogger implements Logger { log(message: string): void { console.log(message); } } ```

Extension Methods

TypeScript also supports extension methods, albeit with some constraints. They can be added to existing classes, providing a way to extend their functionality:

AD
```typescript declare module 'lodash' { interface String { padded(length: number, character?: string): string; } } String.prototype.padded = function(length: number, character = ' '): string { const PADDING_REGEX = /^\s*(\S.*?|\s*)\s*$/; const str = String(this); const padding = str.length > length ? '' : Array.from({ length }).fill(character).join(''); return `${str.padStart(length, padding).replace(PADDING_REGEX, '$1')}`; }; ```

This extension method allows any string to be padded, extending the functionality of the built-in String prototype.

the typescript simple types are shown in this diagram
the typescript simple types are shown in this diagram
Are.na
Are.na
How to set up a TypeScript project
How to set up a TypeScript project
TypeScript vs JavaScript: Which Is Best in 2022
TypeScript vs JavaScript: Which Is Best in 2022
5 open source alternatives to Google Docs
5 open source alternatives to Google Docs
SOLID Principles Explained: A Visual Guide to Better System Design
SOLID Principles Explained: A Visual Guide to Better System Design

Closed for Modification

The 'Closed for Modification' part of OCP means that our code should not be altered once it's deployed. This ensures stability and prevents breaking changes. In TypeScript, final classes and properties help enforce this by preventing accidental modifications.

To achieve this, we can use the `final` keyword to mark a class as non-extendable or properties as non-writable. Let's see how we can implement this.

AD

Final Classes and Properties

Marking a class as `final` prevents it from being extended. Here's an example of a `SettingsService` class with some `final` properties:

an image of a computer screen with the text function and numbers on it, in front of a green background
an image of a computer screen with the text function and numbers on it, in front of a green background
Getting started with Typescript with React Hooks
Getting started with Typescript with React Hooks
an open closed pringle diagram with several different types of words and numbers on it
an open closed pringle diagram with several different types of words and numbers on it
50 Must-Know TypeScript Commands Every Developer Should Save
50 Must-Know TypeScript Commands Every Developer Should Save
Type script Vs JavaScript|webdevelopment||Techy Musk|
Type script Vs JavaScript|webdevelopment||Techy Musk|
How to do object destructuring with types in TypeScript?
How to do object destructuring with types in TypeScript?
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
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
a computer screen with the words typescript on it
a computer screen with the words typescript on it
an open source sign on a yellow background
an open source sign on a yellow background
Object-Oriented Software Principles
Object-Oriented Software Principles
the front cover of an open and closing tags book, with text below it that reads'opening and closing tags most html tags have an opening tag and a
the front cover of an open and closing tags book, with text below it that reads'opening and closing tags most html tags have an opening tag and a
The Ultimate Comparison of Typescript and Javascript - What You Need to Know
The Ultimate Comparison of Typescript and Javascript - What You Need to Know
Cream Elegant Neutral Open Closed Sign A2 Landscape Poster
Cream Elegant Neutral Open Closed Sign A2 Landscape Poster
```typescript class SettingsService { private static readonly finalAPIUrl: string = 'https://api.example.com'; public getAPIUrl(): string { return SettingsService.finalAPIUrl; } } ```

By marking the `finalAPIUrl` as `final`, we ensure it can't be changed once the class is compiled.

In conclusion, applying the Open-Closed Principle in TypeScript can make your code more flexible, maintainable, and easier to extend. By embracing this principle, you can create more robust and adaptable software solutions. So, the next time you're working on a TypeScript project, consider how you can apply OCP to make your code more extensible and less prone to modification. Happy coding!

AD
AD