Lesson 4
Applying SOLID Principles in TypeScript
Introduction

Welcome to the final lesson of the "Applying Clean Code Principles" course! Throughout this course, we've covered vital principles such as DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and the Law of Demeter, all of which are foundational to writing clean and efficient code. In this culminating lesson, we'll explore the SOLID Principles, a set of design principles introduced by Robert C. Martin, commonly known as "Uncle Bob." Understanding SOLID is crucial for creating software that is flexible, scalable, and easy to maintain. Let's dive in and explore these principles together.

SOLID Principles at a Glance

To start off, here's a quick overview of the SOLID Principles and their purposes:

  • Single Responsibility Principle (SRP): Each class or module should only have one reason to change, meaning it should have only one job or responsibility.
  • Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
  • Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of their subclasses without affecting the correctness of the program.
  • Interface Segregation Principle (ISP): No client should be forced to depend on methods it does not use.
  • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

These principles are guidelines that help programmers write code that is easier to understand and more flexible to change, leading to cleaner and more maintainable codebases. Let's explore each principle in detail.

Single Responsibility Principle

The Single Responsibility Principle states that each class should have only one reason to change, meaning it should only have one job or responsibility. This helps in reducing the complexity and enhancing the readability and maintainability of the code. Consider the following:

TypeScript
1class User { 2 // User-related attributes and methods 3} 4 5class UserPrinter { 6 printUserInfo(user: User): void { 7 // Print user information 8 } 9} 10 11class UserDataStore { 12 storeUserData(user: User): void { 13 // Store user data in the database 14 } 15}

In the refactored code, we have three classes, each handling a specific responsibility. This makes the code cleaner and easier to manage.

Open/Closed Principle

The Open/Closed Principle advises that software entities should be open for extension but closed for modification. This allows for enhancing and extending functionalities without altering existing code, reducing errors, and ensuring stable systems. Consider this example:

TypeScript
1interface Shape { 2 calculateArea(): number; 3} 4 5class Rectangle implements Shape { 6 private width: number; 7 private height: number; 8 9 constructor(width: number, height: number) { 10 this.width = width; 11 this.height = height; 12 } 13 14 calculateArea(): number { 15 return this.width * this.height; 16 } 17} 18 19class Circle implements Shape { 20 private radius: number; 21 22 constructor(radius: number) { 23 this.radius = radius; 24 } 25 26 calculateArea(): number { 27 return Math.PI * this.radius * this.radius; 28 } 29} 30 31class AreaCalculator { 32 calculateArea(shape: Shape): number { 33 return shape.calculateArea(); 34 } 35}

Now, new shapes can be added without altering AreaCalculator. This setup adheres to the Open/Closed Principle by leaving the original code unchanged when extending functionalities.

Liskov Substitution Principle

The Liskov Substitution Principle ensures that objects of a subclass should be able to replace objects of a superclass without altering the functionality or causing any errors in the program.

TypeScript
1class Bird { 2 // Common behaviors for all birds 3} 4 5class FlyingBird extends Bird { 6 fly(): void { 7 console.log("Flying"); 8 } 9} 10 11class Ostrich extends Bird { 12 // Specific behaviors for ostriches 13}

By introducing FlyingBird and having only birds that can actually fly inherit from it, we can substitute Bird with Ostrich without errors, adhering to Liskov’s Substitution Principle.

Interface Segregation Principle

The Interface Segregation Principle states that no client should be forced to depend on methods it does not use. Interfaces should be split into smaller, more specific entities so that clients only implement the methods they need:

TypeScript
1interface Workable { 2 work(): void; 3} 4 5interface Eatable { 6 eat(): void; 7} 8 9class Robot implements Workable { 10 work(): void { 11 // Robot work functions 12 } 13} 14 15class Human implements Workable, Eatable { 16 work(): void { 17 // Human work functions 18 } 19 20 eat(): void { 21 // Human eating functions 22 } 23}

Now, Robot only implements the Workable interface, adhering to the Interface Segregation Principle.

Dependency Inversion Principle

The Dependency Inversion Principle dictates that high-level modules should not depend on low-level modules, but both should depend on abstractions. Here's an example:

TypeScript
1interface Switchable { 2 turnOn(): void; 3 turnOff(): void; 4} 5 6class LightBulb implements Switchable { 7 turnOn(): void { 8 console.log("LightBulb turned on"); 9 } 10 11 turnOff(): void { 12 console.log("LightBulb turned off"); 13 } 14} 15 16class Switch { 17 private client: Switchable; 18 19 constructor(client: Switchable) { 20 this.client = client; 21 } 22 23 operate(): void { 24 // Operate on the switchable client 25 } 26}

Now Switch uses the Switchable interface, which can be implemented by any switchable device. This setup allows the Switch class to remain unchanged when introducing new devices, thus following the Dependency Inversion Principle by depending on an abstraction and reducing the system's rigidity.

Review and Next Steps

In this lesson, we delved into the SOLID Principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. These principles guide developers to create code that is maintainable, scalable, and easy to extend or modify. As you prepare for the upcoming practice exercises, remember that applying these principles in real-world scenarios will significantly enhance your coding skills and the quality of your codebase. Good luck, and happy coding! 🎓

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.