Activity 25: SOLID PRINCIPLES in Angular

This will Explain the importance of SOLID principles in software development, highlight how these principles ensure code maintainability, scalability, and readability. This article will cover Angular-specific examples for practical understanding.

S - Single Responsibility Principle (SRP)

A class should have one and only one reason to change. This principle ensures each class focuses on a single functionality.

O - Open/Closed Principle (OCP)

A class should be open for extension but closed for modification.

// PaymentStrategy: Define an interface for payment methods
export interface PaymentStrategy {
  processPayment(amount: number): void;
}

// CreditCardPayment: Implements PaymentStrategy
export class CreditCardPayment implements PaymentStrategy {
  processPayment(amount: number): void {
    console.log(`Processing credit card payment of $${amount}`);
  }
}

// PaymentService: Uses PaymentStrategy
@Injectable({
  providedIn: 'root',
})
export class PaymentService {
  constructor(private paymentStrategy: PaymentStrategy) {}

  makePayment(amount: number) {
    this.paymentStrategy.processPayment(amount);
  }
}

L - Liskov Substitution Principle (LSP)

Subtypes should be substitutable for their base types. This ensure components or services extend functionality without altering behavior.

// BaseService: Base class for APIs
export abstract class BaseService {
  abstract fetchData(): any;
}

// UserService: Extends BaseService
@Injectable({
  providedIn: 'root',
})
export class UserService extends BaseService {
  fetchData() {
    return { id: 1, name: 'John Doe' };
  }
}

I - Interface Segregation Principle (ISP)

A class should not be forced to implement methods it does not use. Uses smaller interfaces to segregate functionalities.

export interface CanEdit {
  edit(): void;
}

export interface CanDelete {
  delete(): void;
}

export class UserManagement implements CanEdit, CanDelete {
  edit() {
    console.log('Editing user...');
  }

  delete() {
    console.log('Deleting user...');
  }
}

D - Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions. Uses tokens for dependency injection.

// Logger Interface
export interface Logger {
  log(message: string): void;
}

// ConsoleLogger Implementation
export class ConsoleLogger implements Logger {
  log(message: string): void {
    console.log(message);
  }
}

// AppModule: Provide ConsoleLogger as Logger
@NgModule({
  providers: [{ provide: Logger, useClass: ConsoleLogger }],
})
export class AppModule {}

These states the benefits of applying SOLID principles in Angular development.

GITHUB LINK: https://github.com/mischiii22/Activity-25.git