Introduction

Welcome! Today, we focus on writing maintainable and scalable software through Code Decoupling and Modularization. We will explore techniques to minimize dependencies, making our code more modular, manageable, and easier to maintain using TypeScript.

What are Code Decoupling and Modularization?

Decoupling ensures our code components are independent by reducing the connections among them. Consider the following TypeScript example:

In the coupled code, calculateArea performs multiple operations, calculating areas for different shapes. In the decoupled code, we split these operations into independent functions, leading to cleaner code.

Conversely, modularization breaks down a program into manageable units or modules.

Understanding Code Dependencies and Why They Matter

Code dependencies occur when one part of the code relies on another part to function. In tightly coupled code, these dependencies are complex, making management and maintenance difficult. By employing decoupling and modularization, we reduce dependencies, leading to cleaner, more organized code.

Consider the following scenario in an e-commerce application:

The Order class performs multiple tasks: calculating the total cost by applying discounts and taxes, and printing an order summary. This complexity makes maintenance difficult.

Using modularization, we decouple responsibilities by creating separate DiscountCalculator and TaxCalculator classes:

Modularization here adheres to the Single Responsibility Principle (SRP) by splitting the responsibilities of discounting, taxation, and order management into separate classes. Additionally, using static in DiscountCalculator and TaxCalculator makes these utility methods stateless, meaning they don't depend on any instance and are reusable across the application.

Introduction to Separation of Concerns

The principle of Separation of Concerns (SoC) allows focusing on a single aspect of a program at one time.

By applying SoC, we broke down the getFullInfo function into separate functions for age, city, and job.

Brick by Brick: Building a Codebase with Modules

Creating modules helps structure our code in a neat and efficient manner. In TypeScript, each file can act as a module:

Using the content of shapes.ts in another file:

The functions for calculating the areas are defined in a separate file — a module in TypeScript. In another file, we import and use these functions.

Lesson Summary and Upcoming Practice

Excellent job today! You've learned about Code Decoupling and Modularization, grasped the value of the Separation of Concerns principle, and explored code dependencies and methods to minimize them using TypeScript. Prepare for some exciting practice exercises to reinforce these concepts. Until next time!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal