SOLID Principles
The SOLID principles are a set of guidelines for writing clean, maintainable, and extensible code. Each principle focuses on a specific aspect of software design and architecture. Let’s go through each of them in typescript:
Single Responsibility Principle (SRP)
A software component (classes, modules, functions, etc.) should have only one reason to change. This means a class should have a single purpose.
By adhering to SRP, we create smaller, focused classes that are easier to understand, test, and maintain.
class Square {
side = 5;
public area(): number {
return this.side * this.side;
}
public perimeter(): number {
return this.side * 4;
}
public draw(): void {
// Draw square
}
public rotate(degree: number): void {
// rotate and render square
}
}In the given code, the Square class violates the Single Responsibility Principle (SRP) because it has multiple responsibilities.
The Square class represents a square shape and contains methods for calculating its area, perimeter, drawing the square, and rotating it. These responsibilities can be categorized as follows:
- Calculation of area and perimeter: The
area()andperimeter()methods are responsible for calculating the area and perimeter of the square. This responsibility is related to the geometric properties of the square. - Drawing the square: The
draw()method is responsible for visually rendering the square on some output device or canvas. This responsibility involves the graphical representation of the square. - Rotating the square: The
rotate()method is responsible for rotating the square and rendering the updated square. This responsibility is related to manipulating the square's orientation.
Ideally, each class should have a single responsibility, but in this case, the Square class combines responsibilities that are related to geometry calculations, drawing, and manipulation. This violates the SRP, making the class less cohesive and harder to maintain.
To adhere to the SRP, you can separate the responsibilities into distinct classes. For example, you could have a SquareCalculator class that solely focuses on area and perimeter calculations, a SquareRenderer class responsible for drawing the square, and a SquareRotator class handling the rotation logic. Each class would have a single responsibility, leading to better code organization, maintainability, and flexibility.
class Square {
side = 5;
}
class SquareCalculator {
private square: Square;
constructor(square: Square) {
this.square = square;
}
public area(): number {
return this.square.side * this.square.side;
}
public perimeter(): number {
return this.square.side * 4;
}
}
class SquareRenderer {
private square: Square;
constructor(square: Square) {
this.square = square;
}
public draw(): void {
// Draw square using the square instance
}
}
class SquareRotator {
private square: Square;
constructor(square: Square) {
this.square = square;
}
public rotate(degree: number): void {
// Rotate the square instance by the given degree
// Render the updated square
}
}By separating the responsibilities into distinct classes, each class has a single responsibility and is focused on a specific aspect of the square’s behaviour. This improves code organization and maintainability, making extending and modifying each class independently easier.
At this point let me provide two definitions that are important to use this principle properly:
Cohesion: This is the degree to which various parts of a software component are related. e.g. there’s high cohesion between area() and perimeter() methods.
Coupling: This is the level of interdependency between various software components. Look at this example:
class Users {
private database: Database;
constructor() {
this.database = new Database();
}
public createUser(name: string): void {
// Database-specific code for creating a user
this.database.connect();
this.database.execute(`INSERT INTO users (name) VALUES ('${name}')`);
this.database.disconnect();
}
public getUser(id: number): string {
// Database-specific code for retrieving a user
this.database.connect();
const result = this.database.execute(`SELECT name FROM users WHERE id = ${id}`);
this.database.disconnect();
return result;
}
}
class Database {
public connect(): void {
// Logic for establishing a database connection
console.log("Connected to the database");
}
public disconnect(): void {
// Logic for closing the database connection
console.log("Disconnected from the database");
}
public execute(query: string): string {
// Logic for executing a database query
console.log(`Executing query: ${query}`);
return "Query result";
}
}In this example, the Users class depends directly on the Database class. It creates an instance of Database in its constructor and calls its methods (connect, execute, disconnect) for database operations such as creating a user and retrieving a user.
This high coupling makes the Users class tightly coupled to the specific Database implementation. Any changes or updates to the database implementation would require modifications in the Users class, violating the principle of separation of concerns.
Let’s correct this using an interface to serve as an abstraction layer, enabling low coupling between the Users class and the concrete implementation of the repository:
class Users {
private userRepository: IUserRepository;
constructor(userRepository: IUserRepository) {
this.userRepository = userRepository;
}
public createUser(name: string): void {
const user = { name };
this.userRepository.save(user);
}
public getUser(id: number): string {
const user = this.userRepository.findById(id);
return user ? user.name : "";
}
}
interface IUser {
name: string;
}
interface IUserRepository {
save(user: IUser): void;
findById(id: number): { id: number; name: string };
}
class DatabaseUserRepository implements IUserRepository {
public save(user: IUser): void {
// Database-specific code for saving a user
console.log(`Saving user ${user.name} to the database`);
// Database query or ORM operation
}
public findById(id: number): { id: number; name: string } {
// Database-specific code for finding a user by ID
console.log(`Finding user with ID ${id} from the database`);
// Database query or ORM operation
return { id, name: "John" }; // Dummy data for demonstration
}
}When SRP is adhered to, our code should have high Cohesion and low Coupling.
Open-Closed Principle (OCP)
Software Components should be open for extension but closed for modification.
This principle promotes the use of abstractions, interfaces, and polymorphism to allow for easy extension of functionality without modifying existing code. This helps maintain stability and reduces the risk of introducing bugs. Also, we do not have to retest every subcomponent because we are not reimplementing existing code.
Let’s consider an example to illustrate this. Suppose we are developing an e-commerce application, and we have a module responsible for handling various payment methods. Initially, we implemented support for credit card payments using a CreditCardPaymentService class:
class CreditCardPaymentService {
processPayment(amount: number): void {
// Logic to process credit card payment
}
}Now, our application has gained popularity, and we need to add support for additional payment methods, such as PayPal and Stripe. Instead of modifying the existing CreditCardPaymentService class to accommodate these changes, we can apply the OCP by creating an abstract PaymentService interface that defines a common contract for all payment methods:
interface PaymentService {
processPayment(amount: number): void;
}Next, implement separate classes for each payment method, all adhering to the PaymentService interface:
class CreditCardPaymentService implements PaymentService {
processPayment(amount: number): void {
// Logic to process credit card payment
console.log(`Processing credit card payment of amount: $${amount}`);
}
}
class PayPalPaymentService implements PaymentService {
processPayment(amount: number): void {
// Logic to process PayPal payment
console.log(`Processing PayPal payment of amount: $${amount}`);
}
}
class StripePaymentService implements PaymentService {
processPayment(amount: number): void {
// Logic to process Stripe payment
console.log(`Processing Stripe payment of amount: $${amount}`);
}
}With this approach, the existing CreditCardPaymentService remains unchanged, and we introduce new classes for PayPal and Stripe payments without modifying the existing code. This fulfils the "closed for modification" aspect of the OCP.
Get Godson Ikhide Atakpu’s stories in your inbox
Join Medium for free to get updates from this writer.
To support different payment methods dynamically, we create an object of the required payment class and pass that as an argument:
// Usage example
function makePayment(paymentService: PaymentService, amount: number): void {
paymentService.processPayment(amount);
}
const creditCardPaymentService = new CreditCardPaymentService();
const payPalPaymentService = new PayPalPaymentService();
const stripePaymentService = new StripePaymentService();
makePayment(creditCardPaymentService, 100); // Output: Processing credit card payment of amount: $100
makePayment(payPalPaymentService, 50); // Output: Processing PayPal payment of amount: $50
makePayment(stripePaymentService, 200); // Output: Processing Stripe payment of amount: $200The function makePayment is able to process payments using any payment service implementation without modifying its code. This demonstrates the open-for-extension, closed-for-modification nature of the OCP.
Liskov Substitution Principle (LSP)
Objects of a superclass should be replaceable with objects of its subclasses without altering the correctness of the program.
We can leverage interfaces and abstract classes to ensure adherence to LSP, enabling us to interchangeably use different implementations of an interface without unexpected behaviour.
Let’s say we have a class that represents a product item being sold by a business and this class contains a method to calculate the discount:
class Product {
protected discount = 20;
public getDiscount() {
return this.discount;
}
}
and suppose they want to introduce their own line of similar products but with an extra discount:
class InHouseProduct extends Product {
public applyExtraDiscount() {
return this.discount * 1.5;
}
}Instead of using an if statement to conditionally select which of the discount calculation functions to call, we should be able to replace the function getDiscount with the implementation for applyExtraDiscount from the Product subtype:
interface Item {
getDiscount(): number;
}
class Product implements Item {
protected discount = 20;
public getDiscount() {
return this.discount;
}
}
class InHouseProduct extends Product {
public getDiscount() {
return this.applyExtraDiscount(); // You can simply substitute the implementation of getDiscount with the correct function
}
public applyExtraDiscount() {
return this.discount * 1.5;
}
}
const milk = new InHouseProduct();
const sugar = new Product();
console.log(milk.getDiscount()); // 30
console.log(sugar.getDiscount()); // 20The Interface Segregation Principle (ISP)
No client should be forced to depend on objects it does not use.
ISP encourages the creation of specific interfaces that are tailored to the needs of individual clients instead of having large, monolithic interfaces. This helps avoid unnecessary dependencies and promotes a decoupled design. You can define smaller, focused interfaces that clearly outline the required functionality for specific use cases.
Let’s say we have 3 types of cars: Sports car, Family car, Utility truck. Each of these has specific features that the other two don’t. To obey this principle, have separate interfaces for each of them rather than one big interface to fit all car types. If a supercar is created that transcends all the features of the three car types, you simply implement all of the interfaces on the class:
interface SportsCar {
accelerate(): void;
brake(): void;
drift(): void;
activateTurbo(): void;
}
interface FamilyCar {
openTrunk(): void;
adjustSeat(): void;
lockDoors(): void;
activateChildLock(): void;
}
interface UtilityTruck {
tow(): void;
loadCargo(): void;
unloadCargo(): void;
extendBed(): void;
}
// Sports Car class
class SportsCar implements SportsCar {
accelerate(): void {}
brake(): void {}
drift(): void {}
activateTurbo(): void {}
}
// Family Car class
class FamilyCar implements FamilyCar {
openTrunk(): void {}
adjustSeat(): void {}
lockDoors(): void {}
activateChildLock(): void {}
}
// Utility Truck class
class UtilityTruck implements UtilityTruck {
tow(): void {}
loadCargo(): void {}
unloadCargo(): void {}
extendBed(): void {}
}
// Supercar class that combines all features
class Supercar implements SportsCar, FamilyCar, UtilityTruck {
accelerate(): void {}
brake(): void {}
drift(): void {}
activateTurbo(): void {}
openTrunk(): void {}
adjustSeat(): void {}
lockDoors(): void {}
activateChildLock(): void {}
tow(): void {}
loadCargo(): void {}
unloadCargo(): void {}
extendBed(): void {}
}Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
Let’s look at an example of two Animal owner classes that require a Dog and Cat class respectively:
class Dog {
makeSound() {
console.log("Dog is barking.");
}
}
class Cat {
makeSound() {
console.log("Cat is meowing.");
}
}
// High-level module that directly depends on concrete implementations
class AnimalOwner1 {
private dog: Dog;
constructor() {
this.dog = new Dog();
}
interactWithAnimal() {
this.dog.makeSound();
}
}
class AnimalOwner2 {
private cat: Cat;
constructor() {
this.cat = new Cat();
}
interactWithAnimal() {
this.cat.makeSound();
}
}
// Usage
const owner1 = new AnimalOwner1();
owner1.interactWithAnimal(); // Output: "Dog is barking."
const owner2 = new AnimalOwner2();
owner2.interactWithAnimal(); // Output: "Cat is meowing."In this example, the AnimalOwner1 and AnimalOwner2 classes directly depend on the concrete implementations of Dog and Cat, violating the DIP. Instead of depending on abstractions, it tightly couples itself to specific concrete classes.
This approach leads to several issues:
- Tight coupling: The
AnimalOwnerclasses are tightly coupled to the concrete implementations ofDogandCat. If there are any changes or additional animal types, theAnimalOwnerclass needs to be modified directly. - Lack of flexibility: The
AnimalOwnerclasses cannot easily be extended to support different types of animals or alternate implementations. Adding a new animal type would require modifying theAnimalOwnerclasses themselves. - Testing difficulties: It becomes challenging to test the
AnimalOwnerclass in isolation or with different animal implementations. Testability is reduced due to the direct dependency on concrete classes.
To adhere to the DIP, we would need to introduce an abstraction (interface or base class) representing the common behaviour of animals and AnimalOwner classes depend on that abstraction rather than concrete classes. By doing so, we would achieve loose coupling and allow for greater flexibility in the system.
// Abstraction: Animal interface
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound() {
console.log("Dog is barking.");
}
}
class Cat implements Animal {
makeSound() {
console.log("Cat is meowing.");
}
}
// High-level module that directly depends on concrete implementations
class AnimalOwner {
private animal: Animal;
constructor(animal: Animal) {
this.animal = animal;
}
interactWithAnimal() {
this.animal.makeSound();
}
}
// Usage
const owner1 = new AnimalOwner(new Dog());
owner1.interactWithAnimal(); // Output: "Dog is barking."
const owner2 = new AnimalOwner(new Cat());
owner2.interactWithAnimal(); // Output: "Cat is meowing."By applying these SOLID principles, we create code that is modular, flexible, and easier to understand, test, and maintain. They promote loose coupling, high cohesion, and adherence to good software design practices. Applying these principles will improve the overall quality and maintainability of our codebase.






