open closed principle example typescript

Understanding TypeScript: Open-Closed Principle in Action

By Emily Martinez
AD

The Open-Closed Principle (OCP) is a fundamental SOLID principle that guide software design by specifying that software entities (like classes, modules, functions) should be open for extension and closed for modification. This principle is widely accepted and applied in various programming languages, including TypeScript. Let's delve into OCP, its benefits, and explore practical TypeScript examples adhering to this principle.

Implementing the Open-Closed Principle in TypeScript helps create more maintainable, flexible, and reusable code. By designing modules that can be extended without modifying their existing code, we promote code encapsulation and minimize the risk of introducing bugs.

Understanding the Open-Closed Principle in TypeScript

The OCP essence in TypeScript lies in creating plugins, hooks, and extension points that allow external code to interact with your module's functionality without altering its core logic. To demonstrate, let's consider a simple logging system.

AD
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+
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide
HTML #17: Opening, Closing & Void Elements Explained | Complete Beginner Guide

Initially, we might have a basic logger module that writes logs to the console:

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

Implementing Logger Decorators

Instead of directly modifying the Logger class, we can create a decorator pattern to extend its functionality:

What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
What Is Closure In Javascript, Javascript Closure Example, How To Use Closures In Javascript, Javascript Closure Explanation, Javascript Practice Questions, Choosing Between Java And Javascript, Javascript Programming Concepts, Recursive Javascript Function, Javascript Apply Call Bind Difference
25 TYPESCRIPT TRICKS EVERY DEVELOPER SHOULD KNOW
25 TYPESCRIPT TRICKS EVERY DEVELOPER SHOULD KNOW
10 Clean Code Principles for Writing Better TypeScript
10 Clean Code Principles for Writing Better TypeScript
```typescript interface LoggerDecorator { log(message: string): void; } class ConsoleLogger implements LoggerDecorator { constructor(private logger: Logger) {} log(message: string) { this.logger.log(`[Console] ${message}`); } } ```

Adding More Log Destinations

Now, we can easily add more log destinations, like a file logger:

```typescript class FileLogger implements LoggerDecorator { constructor(private logger: Logger, private filePath: string) {} log(message: string) { this.logger.log(`[File-${this.filePath}] ${message}`); } } ```

Applying OCP to DI and Middleware

A common use case for OCP is in dependency injection (DI) systems and middleware pipelines. By maintaining an open, extendsible structure, we encourage developers to contribute new functionality without disrupting existing code.

AD

Injecting Services with Decorators

Consider a service with injected dependencies. Applying OCP allows us to add or modify dependencies without touching the service class:

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
a book cover with the title underneath it and an image of a programming program on top
a book cover with the title underneath it and an image of a programming program on top
50 Must-Know TypeScript Commands Every Developer Should Save
50 Must-Know TypeScript Commands Every Developer Should Save
The Open-Closed Principle at an Architectural Level
The Open-Closed Principle at an Architectural Level
the word open is written in black on a gray background
the word open is written in black on a gray background
```typescript function inject(serviceKey: string) { return (constructor: Function) => { constructor.prototype.service = (serviceContainer as any)[serviceKey]; }; } @Injectable() class MyService { @inject('logger') private logger: LoggerDecorator; doSomething() { // ... use logger here ... } } ```

Building Middleware Pipelines

Middleware pipelines follow OCP by providing extension points for new middlewares:

```typescript type Middleware = (req: any, res: any, next: () => void) => void; class Pipeline { private middlewares: Middleware[] = []; use(middleware: Middleware) { this.middlewares.push(middleware); } handleRequest(req, res) { let next = () => {}; const handleMiddleware = (i: number) => { if (i === this.middlewares.length) return next(); const middleware = this.middlewares[i]; middleware(req, res, () => handleMiddleware(i + 1)); }; handleMiddleware(0); } } ```

Implementing the Open-Closed Principle in your TypeScript projects promotes a modular, extensible, and maintainable codebase. By embracing OCP, you invite collaborations, allow for future growth, and.dir=shield yourself from the devastating impact of rip-and-replace refactoring. Embrace the open and close your projects today!

AD
an image of a diagram that shows how to use the apis for web development
an image of a diagram that shows how to use the apis for web development
the typescript simple types are shown in this diagram
the typescript simple types are shown in this diagram
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
OPEN
OPEN
an open / closed sign with the words pringle ocf
an open / closed sign with the words pringle ocf
the front end and back end of a web page with different font styles on it
the front end and back end of a web page with different font styles on it
a purple screen with the text closure
a purple screen with the text closure
How to do object destructuring with types in TypeScript?
How to do object destructuring with types in TypeScript?
TypeScript Partial: Simplify Object Updates with Optional Properties
TypeScript Partial: Simplify Object Updates with Optional Properties
open
open
the words open are black and white
the words open are black and white
a black background with text that reads typescript
a black background with text that reads typescript
a computer screen with some type of programming program on it's side and the text, bad example function green name
a computer screen with some type of programming program on it's side and the text, bad example function green name
Getting started with Typescript with React Hooks
Getting started with Typescript with React Hooks
AD