<question_list>
<question_item>
How does the Single Responsibility Principle (SRP) apply in TypeScript, and can you provide an example of implementing SRP in a TypeScript class?
The Single Responsibility Principle (SRP) states that a class should have only one reason to change, meaning it should have only one job or responsibility. Applying SRP in TypeScript ensures that classes are cleaner, more maintainable, and easier to understand.
Here's how you might implement SRP in TypeScript:
// Violating SRP
class UserService {
createUser(userData: any) {
// Logic to create a user
}
validateUserData(userData: any) {
// Logic to validate user data
}
sendWelcomeEmail(userEmail: string) {
// Logic to send a welcome email
}
}
In the above code, the UserService class has multiple responsibilities:
- Creating users
- Validating user data
- Sending emails
To adhere to SRP, we can separate these responsibilities:
class UserCreator {
constructor(private validator: UserValidator, private emailSender: EmailSender) {}
createUser(userData: any) {
if (this.validator.validate(userData)) {
// Logic to create a user
this.emailSender.sendWelcomeEmail(userData.email);
}
}
}
class UserValidator {
validate(userData: any): boolean {
// Validation logic
return true;
}
}
class EmailSender {
sendWelcomeEmail(userEmail: string) {
// Email sending logic
}
}
Now, each class has a single responsibility:
UserValidator handles validation.
EmailSender handles sending emails.
UserCreator orchestrates the creation process.
Explanation:
By applying SRP, we make our code modular and easier to test. If there's a change in the email sending process, we only need to modify the EmailSender class. This separation of concerns leads to better maintainability and scalability.
In TypeScript, we can achieve OCP using inheritance, interfaces, and polymorphism.
Example:
Suppose we have a Shape interface and different shape classes:
interface Shape {
area(): number;
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
area(): number {
return this.width * this.height;
}
}
class Circle implements Shape {
constructor(private radius: number) {}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
Now, we have a function that calculates the total area of multiple shapes:
function totalArea(shapes: Shape[]): number {
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
}
If we need to add a new shape, like a Triangle, we can extend the system without modifying the existing classes or the totalArea function:
class Triangle implements Shape {
constructor(private base: number, private height: number) {}
area(): number {
return 0.5 * this.base * this.height;
}
}
Explanation:
By programming to an interface (Shape), we've made the totalArea function and existing classes closed for modification but open for extension. We can add new shapes without changing existing code, adhering to the Open/Closed Principle.
Violation Example:
Consider a class hierarchy for birds:
class Bird {
fly(): void {
console.log("Flying");
}
}
class Eagle extends Bird {}
class Penguin extends Bird {
fly(): void {
// Penguins can't fly!
throw new Error("Penguins can't fly!");
}
}
Using the above classes:
function letBirdFly(bird: Bird) {
bird.fly();
}
letBirdFly(new Eagle()); // Works fine
letBirdFly(new Penguin()); // Throws an error
Explanation:
In this example, substituting Penguin for Bird violates LSP because Penguin cannot fulfill the contract of Bird (ability to fly). This can lead to runtime errors.
Solution:
Refactor the hierarchy to respect LSP:
class Bird {
// Common properties and methods for all birds
}
interface FlyingBird {
fly(): void;
}
class Eagle extends Bird implements FlyingBird {
fly(): void {
console.log("Flying");
}
}
class Penguin extends Bird {
// Penguins don't implement FlyingBird
}
function letBirdFly(bird: FlyingBird) {
bird.fly();
}
letBirdFly(new Eagle()); // Works fine
// letBirdFly(new Penguin()); // TypeScript compile-time error
Explanation:
By segregating the fly method into a separate interface FlyingBird, we prevent non-flying birds from being misused where flying birds are expected, thus adhering to LSP.
Example Without ISP:
interface Worker {
work(): void;
eat(): void;
}
class HumanWorker implements Worker {
work(): void {
console.log("Human is working");
}
eat(): void {
console.log("Human is eating");
}
}
class RobotWorker implements Worker {
work(): void {
console.log("Robot is working");
}
eat(): void {
// Robots don't eat
throw new Error("Robot cannot eat");
}
}
Problem:
RobotWorker is forced to implement the eat method, which it doesn't need.
Applying ISP:
Separate the interfaces:
interface Workable {
work(): void;
}
interface Eatable {
eat(): void;
}
class HumanWorker implements Workable, Eatable {
work(): void {
console.log("Human is working");
}
eat(): void {
console.log("Human is eating");
}
}
class RobotWorker implements Workable {
work(): void {
console.log("Robot is working");
}
}
Explanation:
By splitting Worker into Workable and Eatable, we allow classes to implement only the interfaces relevant to them. RobotWorker no longer needs to implement eat, adhering to the Interface Segregation Principle.
- 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.
This principle helps in creating loosely coupled code.
Example Without DIP:
class MySQLDatabase {
connect() {
// Connect to MySQL database
}
}
class UserService {
private db: MySQLDatabase;
constructor() {
this.db = new MySQLDatabase();
}
getUser(id: number) {
this.db.connect();
// Logic to get user from database
}
}
Problem:
UserService depends directly on MySQLDatabase. If we want to switch to a different database, we need to modify UserService.
Applying DIP:
Introduce an abstraction:
interface Database {
connect(): void;
}
class MySQLDatabase implements Database {
connect() {
// Connect to MySQL database
}
}
class PostgreSQLDatabase implements Database {
connect() {
// Connect to PostgreSQL database
}
}
class UserService {
constructor(private db: Database) {}
getUser(id: number) {
this.db.connect();
// Logic to get user from database
}
}
Now, we can inject any database that implements the Database interface:
const mySQLDb = new MySQLDatabase();
const userServiceMySQL = new UserService(mySQLDb);
const postgresDb = new PostgreSQLDatabase();
const userServicePostgres = new UserService(postgresDb);
Explanation:
By depending on the abstraction (Database interface), UserService is decoupled from the concrete implementations of databases. This makes the code more flexible and easier to maintain, as high-level modules (UserService) do not depend on low-level modules (MySQLDatabase, PostgreSQLDatabase).
Generic Class Example:
class Stack<T> {
private elements: T[] = [];
push(element: T) {
this.elements.push(element);
}
pop(): T | undefined {
return this.elements.pop();
}
peek(): T | undefined {
return this.elements[this.elements.length - 1];
}
}
Usage:
const numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
console.log(numberStack.pop()); // Outputs: 20
const stringStack = new Stack<string>();
stringStack.push("hello");
stringStack.push("world");
console.log(stringStack.pop()); // Outputs: "world"
Explanation:
By defining Stack<T>, we create a stack that can hold elements of any type T. This ensures type safety; for instance, numberStack can only hold numbers, and trying to push a string into it would result in a compile-time error. Generics improve code reusability by allowing the same class to work with different data types.
Decorator Example:
Suppose we want to log when a method is called.
function Log(target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${String(propertyKey)} with`, args);
const result = originalMethod.apply(this, args);
console.log(`Result of ${String(propertyKey)}:`, result);
return result;
};
return descriptor;
}
class Calculator {
@Log
add(a: number, b: number): number {
return a + b;
}
}
const calc = new Calculator();
calc.add(2, 3);
Output:
Calling add with [2, 3]
Result of add: 5
Explanation:
The @Log decorator wraps the original add method, adding logging before and after its execution. Decorators provide a way to write cleaner and more expressive code by separating cross-cutting concerns (like logging) from the business logic.
Note:
Decorators in TypeScript are an experimental feature and require enabling the "experimentalDecorators": true compiler option in tsconfig.json.
Abstract Class Example:
abstract class Animal {
constructor(protected name: string) {}
abstract makeSound(): void;
move(): void {
console.log(`${this.name} is moving.`);
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Bark!");
}
}
const dog = new Dog("Buddy");
dog.makeSound(); // Outputs: Bark!
dog.move(); // Outputs: Buddy is moving.
// const animal = new Animal("Generic"); // Error: Cannot create an instance of an abstract class.
Interfaces vs. Abstract Classes:
-
Interfaces:
- Define a contract that classes can implement.
- Cannot contain implementation details (method bodies).
- Classes can implement multiple interfaces.
-
Abstract Classes:
- Can contain both abstract methods (without implementation) and concrete methods (with implementation).
- Provide a partial implementation that subclasses can inherit and extend.
- A class can extend only one abstract class.
Interface Example:
interface Flyable {
fly(): void;
}
class Bird implements Flyable {
fly(): void {
console.log("Flying");
}
}
Explanation:
Use interfaces when you need to define a contract without any implementation. Use abstract classes when you need to provide common base functionality along with definitions for abstract methods that subclasses must implement.
Implementation in TypeScript:
- Define an interface for the strategy:
interface SortingStrategy {
sort(data: number[]): number[];
}
- Implement concrete strategies:
class BubbleSortStrategy implements SortingStrategy {
sort(data: number[]): number[] {
// Implement bubble sort
console.log("Sorting using bubble sort");
// Return sorted data
return data;
}
}
class QuickSortStrategy implements SortingStrategy {
sort(data: number[]): number[] {
// Implement quick sort
console.log("Sorting using quick sort");
// Return sorted data
return data;
}
}
- Create a context that uses a strategy:
class Sorter {
constructor(private strategy: SortingStrategy) {}
setStrategy(strategy: SortingStrategy) {
this.strategy = strategy;
}
sort(data: number[]): number[] {
return this.strategy.sort(data);
}
}
- Usage:
const sorter = new Sorter(new BubbleSortStrategy());
let data = [3, 2, 1];
data = sorter.sort(data);
sorter.setStrategy(new QuickSortStrategy());
data = sorter.sort(data);
Explanation:
By implementing the Strategy pattern, you can change the sorting algorithm (SortingStrategy) at runtime without modifying the Sorter class. This provides flexibility and adheres to the Open/Closed Principle.
Creating Mixins:
- Define mixin functions:
function Jumpable<T extends Constructor>(Base: T) {
return class extends Base {
jump() {
console.log("Jumping");
}
};
}
function Eatable<T extends Constructor>(Base: T) {
return class extends Base {
eat() {
console.log("Eating");
}
};
}
type Constructor = new (...args: any[]) => {};
- Create a base class and apply mixins:
class Animal {
move() {
console.log("Moving");
}
}
class Dog extends Jumpable(Eatable(Animal)) {}
const dog = new Dog();
dog.move(); // Outputs: Moving
dog.eat(); // Outputs: Eating
dog.jump(); // Outputs: Jumping
Explanation:
- Traditional Inheritance: A class extends a single base class, inheriting its properties and methods.
- Mixins: A class can combine multiple behaviors from mixin functions, allowing for multiple inheritance of behavior.
Mixins provide flexibility by enabling classes to incorporate behaviors from multiple sources, which is not possible with classical single inheritance.
- public: Accessible anywhere.
- private: Accessible only within the class.
- protected: Accessible within the class and its subclasses.
Example:
class Person {
public name: string;
private age: number;
protected address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
public getAge(): number {
return this.age;
}
protected getAddress(): string {
return this.address;
}
}
class Employee extends Person {
private salary: number;
constructor(name: string, age: number, address: string, salary: number) {
super(name, age, address);
this.salary = salary;
}
public getEmployeeInfo(): string {
return `${this.name}, ${this.getAge()}, ${this.getAddress()}, ${this.salary}`;
}
}
const emp = new Employee("Alice", 30, "123 Main St", 50000);
console.log(emp.name); // Accessible
console.log(emp.getAge()); // Accessible
// console.log(emp.age); // Error: 'age' is private
// console.log(emp.address); // Error: 'address' is protected
Explanation:
- public
name: Accessible from anywhere.
- private
age: Accessible only within Person. Even Employee cannot access it directly.
- protected
address: Accessible within Person and Employee, but not from outside.
Employee can access getAddress because it is protected.
Encapsulation is achieved by restricting access to class members, enforcing control over how data is accessed and modified.
A union type describes a value that can be one of several types.
Example:
function formatCommandLine(input: string | string[]) {
if (typeof input === "string") {
return input.trim();
} else {
return input.map(str => str.trim()).join(" ");
}
}
Intersection Types (&):
An intersection type combines multiple types into one. The new type has all the members of the types it is composed of.
Example:
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface DataResponse {
data: string[];
}
type ApiResponse = ErrorHandling & DataResponse;
const response: ApiResponse = {
success: true,
data: ["item1", "item2"],
};
Polymorphism with Union Types:
Union types enable functions to accept arguments of different types, enhancing polymorphism.
Example:
class Dog {
bark() {
console.log("Woof!");
}
}
class Cat {
meow() {
console.log("Meow!");
}
type Pet = Dog | Cat;
function speak(pet: Pet) {
if (pet instanceof Dog) {
pet.bark();
} else if (pet instanceof Cat) {
pet.meow();
}
}
Explanation:
Using union types, we can create flexible interfaces and functions that can operate on multiple types, which is a form of polymorphism. Intersection types allow us to compose new types from existing ones, which can be useful in mixin patterns.
Example:
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor to prevent direct instantiation
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod() {
console.log("Singleton method called");
}
}
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // Outputs: true
singleton1.someMethod(); // Outputs: Singleton method called
Explanation:
- The constructor is private, so the class cannot be instantiated from outside.
- The static
getInstance method controls the creation of the instance.
- If an instance already exists, it returns that instance; otherwise, it creates a new one.
- This ensures that only one instance of
Singleton exists in the application.
Note:
Implementing singletons should be done cautiously, as they can introduce global state and complicate testing.
Example:
class Calculator {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: any, b: any): any {
return a + b;
}
}
const calc = new Calculator();
console.log(calc.add(1, 2)); // Outputs: 3
console.log(calc.add("Hello, ", "World!")); // Outputs: Hello, World!
Explanation:
- Multiple method signatures are declared for
add.
- The actual implementation handles the general case.
- TypeScript uses the signatures to perform type checking at compile-time.
- This allows
add to accept both numbers and strings, exhibiting polymorphic behavior.
Note:
Only the implementation signature (the last one with the method body) contains the implementation. The overload signatures are for type checking purposes.
Structural Typing:
If two types have the same structure, they are considered compatible.
Example:
class Person {
name: string;
}
class Employee {
name: string;
}
let p: Person = new Employee(); // Allowed, structures are compatible
Nominal Typing:
In nominal typing (used in languages like Java), types are considered compatible only if they have the same name or explicitly declare compatibility.
Impact on Class Design:
Example of Structural Typing in Functions:
interface Point2D {
x: number;
y: number;
}
interface Point3D {
x: number;
y: number;
z: number;
}
function printPoint(point: Point2D) {
console.log(`x: ${point.x}, y: ${point.y}`);
}
const point3D: Point3D = { x: 1, y: 2, z: 3 };
printPoint(point3D); // Allowed, because point3D has at least x and y
Explanation:
Even though Point3D is not explicitly a Point2D, it matches the structure required by printPoint, so it is allowed.
Example: Creating a Readonly Type
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = { id: 1, name: "Alice" };
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
Creating a Nullable Type
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
type NullableUser = Nullable<User>;
const nullableUser: NullableUser = { id: null, name: null };
Explanation:
- Mapped Types Syntax:
[P in keyof T]: ...
- Iterates over each property
P in T.
- Constructs a new type with transformed properties.
- Use Cases:
- Creating read-only, nullable, or partial versions of types.
- Enforcing certain constraints or applying transformations generically.
Built-in Mapped Types:
TypeScript provides built-in mapped types like Partial<T>, Required<T>, Readonly<T>, etc.
Example Using Built-in Partial:
type PartialUser = Partial<User>;
const partialUser: PartialUser = { name: "Bob" }; // 'id' is optional
Conclusion:
Mapped types enhance code reusability by allowing developers to create versatile type transformations, making the type system more powerful and expressive.
Syntax:
T extends U ? X : Y
If T extends U, the type resolves to X; otherwise, it resolves to Y.
Example:
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
Using Conditional Types for Type Transformation:
type Flatten<T> = T extends Array<infer U> ? U : T;
type Str = Flatten<string[]>; // string
type Num = Flatten<number>; // number
function flatten<T>(x: T): Flatten<T> {
if (Array.isArray(x)) {
return x[0];
} else {
return x;
}
}
Explanation:
infer U: Extracts the type of the array elements.
- Usage in Generics:
- Conditional types can be used within generic types or functions to adapt behavior based on the provided type arguments.
- Type Guards and Conditional Types:
function getValue<T>(x: T): T extends boolean ? "boolean" : "other" {
if (typeof x === "boolean") {
return "boolean" as any;
} else {
return "other" as any;
}
}
const val1 = getValue(true); // Type is "boolean"
const val2 = getValue(123); // Type is "other"
Conclusion:
Conditional types make the type system more expressive, allowing for advanced typing scenarios where types can change based on conditions, leading to safer and more flexible code.
Implementation in TypeScript:
- Define the Observer Interface:
interface Observer {
update(subject: Subject): void;
}
- Define the Subject Class:
class Subject {
private observers: Observer[] = [];
private _state: number = 0;
get state() {
return this._state;
}
set state(value: number) {
this._state = value;
this.notifyAll();
}
attach(observer: Observer) {
this.observers.push(observer);
}
detach(observer: Observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notifyAll() {
for (const observer of this.observers) {
observer.update(this);
}
}
}
- Implement Concrete Observers:
class ConcreteObserverA implements Observer {
update(subject: Subject) {
if (subject.state < 10) {
console.log("ConcreteObserverA: Reacted to the event.");
}
}
}
class ConcreteObserverB implements Observer {
update(subject: Subject) {
if (subject.state >= 10) {
console.log("ConcreteObserverB: Reacted to the event.");
}
}
}
- Usage Example:
const subject = new Subject();
const observerA = new ConcreteObserverA();
const observerB = new ConcreteObserverB();
subject.attach(observerA);
subject.attach(observerB);
subject.state = 5;
// Output:
// ConcreteObserverA: Reacted to the event.
subject.state = 15;
// Output:
// ConcreteObserverB: Reacted to the event.
Explanation:
- The
Subject maintains a list of observers and notifies them when its state changes.
- Observers implement the
Observer interface and define how they react to state changes.
- This pattern decouples the subject from the observers, promoting loose coupling and adherence to the Open/Closed Principle.
Example:
class Animal {
move() {
console.log("Animal is moving");
}
}
class Dog extends Animal {
move() {
console.log("Dog is running");
}
bark() {
console.log("Bark!");
}
}
const animal = new Animal();
animal.move(); // Outputs: Animal is moving
const dog = new Dog();
dog.move(); // Outputs: Dog is running
dog.bark(); // Outputs: Bark!
Using super:
If the subclass wants to extend the behavior of the superclass method:
class Cat extends Animal {
move() {
super.move(); // Calls Animal's move method
console.log("Cat is stalking");
}
}
const cat = new Cat();
cat.move();
// Outputs:
// Animal is moving
// Cat is stalking
Explanation:
- Overriding: The subclass
Dog provides its own implementation of move.
super Keyword: In Cat, super.move() calls the superclass (Animal) move method before executing additional code.
- Purpose:
- Allows subclasses to refine or extend the behavior of inherited methods.
- Promotes code reuse and adherence to the DRY (Don't Repeat Yourself) principle.
Implementation in TypeScript:
- Define an Interface for Products:
interface Shape {
draw(): void;
}
- Implement Concrete Products:
class Circle implements Shape {
draw(): void {
console.log("Drawing a Circle");
}
}
class Square implements Shape {
draw(): void {
console.log("Drawing a Square");
}
}
- Create a Factory Class:
class ShapeFactory {
createShape(shapeType: string): Shape | null {
if (shapeType === "circle") {
return new Circle();
} else if (shapeType === "square") {
return new Square();
} else {
return null;
}
}
}
- Usage Example:
const factory = new ShapeFactory();
const shape1 = factory.createShape("circle");
shape1?.draw(); // Outputs: Drawing a Circle
const shape2 = factory.createShape("square");
shape2?.draw(); // Outputs: Drawing a Square
Explanation:
- The client code interacts with the
ShapeFactory to create Shape objects.
- The
ShapeFactory hides the instantiation logic and decides which concrete class to instantiate based on input.
- The client code depends on the
Shape interface, not concrete implementations, promoting loose coupling.
Benefits:
- Centralizes object creation.
- Eases adding new products (shapes) without modifying client code.
- Adheres to the Open/Closed Principle.
Example Without Parameter Properties:
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Using Parameter Properties:
class Person {
constructor(public name: string, public age: number) {}
}
const person = new Person("Alice", 30);
console.log(person.name); // Outputs: Alice
console.log(person.age); // Outputs: 30
Explanation:
- By adding
public (or private, protected, readonly) before the constructor parameters, TypeScript automatically:
- Declares the property on the class.
- Initializes the property with the value passed to the constructor.
- This reduces boilerplate code, making the class definition more concise.
Benefits:
- Simplifies class constructors.
- Improves code readability.
- Ensures consistency between constructor parameters and class properties.
Example:
class ImmutablePoint {
constructor(public readonly x: number, public readonly y: number) {}
}
const point = new ImmutablePoint(10, 20);
console.log(point.x); // Outputs: 10
// point.x = 30; // Error: Cannot assign to 'x' because it is a read-only property.
Benefits:
- Immutability: Ensures that the property value cannot be changed after initialization, promoting safer and more predictable code.
- Intentionality: Makes the developer's intention clear that the property should not be modified.
- Type Safety: Allows TypeScript to catch attempts to modify read-only properties at compile time.
Readonly with Interfaces:
interface Person {
readonly id: number;
name: string;
}
const person: Person = { id: 1, name: "Alice" };
// person.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
Readonly Array:
const numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
Conclusion:
Using readonly enhances the robustness of your code by preventing unintended mutations, which can help prevent bugs and maintain data integrity.
Interface:
- Can be extended (implements or extends).
- Can merge declarations (interface merging).
- Ideal for defining contracts in OOP (classes implementing interfaces).
Type Alias:
- Can define primitive types, union types, and tuple types, not just object shapes.
- Cannot be reopened to add new properties.
Examples:
Defining an Interface:
interface Point {
x: number;
y: number;
}
class Coordinate implements Point {
x: number;
y: number;
}
interface Point {
z: number; // Merging - Point now has x, y, and z
}
Defining a Type Alias:
type Point = {
x: number;
y: number;
};
type ID = number | string;
Differences:
-
Declaration Merging:
interface Point { x: number; }
interface Point { y: number; }
- Now
Point has both x and y.
- Type aliases cannot merge declarations.
-
Extending Types:
- Interfaces can
extend or be implements by classes.
- Type aliases cannot be implemented but can use intersection types.
When to Use:
-
Use interface when:
- Defining the shape of an object that will be implemented by classes.
- You need to take advantage of declaration merging or extension.
-
Use type when:
- Defining complex types, such as union types, tuples, or mapped types.
- You need to define a type alias for a primitive type.
Conclusion:
In OOP, interface is generally preferred for defining contracts that classes implement, promoting clear object-oriented design principles.
Example of Custom Error Class:
class ValidationError extends Error {
constructor(public message: string) {
super(message);
this.name = "ValidationError";
Object.setPrototypeOf(this, ValidationError.prototype);
}
}
function validateUserInput(input: string) {
if (input.trim() === "") {
throw new ValidationError("Input cannot be empty.");
}
// Continue processing
}
try {
validateUserInput(" ");
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Validation Failed: ${error.message}`);
} else {
console.error("An unexpected error occurred.");
}
}
Explanation:
- Extending
Error: The custom ValidationError extends the built-in Error class.
- Setting Prototype:
Object.setPrototypeOf is used to maintain the prototype chain, which is necessary for custom error types.
- Throwing and Catching: The function
validateUserInput throws a ValidationError when validation fails.
- Type Guard: Using
instanceof in the catch block to handle specific error types.
Importance in OOP Design:
- Specificity: Custom errors provide more detailed information about what went wrong, improving debuggability.
- Control Flow: Allows different error types to be handled differently.
- Abstraction: Encapsulates error-related logic within classes, adhering to OOP principles.
Conclusion:
Using custom errors enhances the robustness of applications by providing clear and specific error handling mechanisms, which is a key aspect of good OOP design.
Inheritance Example:
class Animal {
move() {
console.log("Moving");
}
}
class Bird extends Animal {
fly() {
console.log("Flying");
}
}
class Penguin extends Bird {
fly() {
// Penguins can't fly!
throw new Error("Penguins can't fly!");
}
}
Problem:
Penguin inherits fly, which doesn't make sense.
- Violates Liskov Substitution Principle.
Composition Example:
Define behaviors as separate classes:
class Movable {
move() {
console.log("Moving");
}
}
class Flyable {
fly() {
console.log("Flying");
}
}
class Bird {
constructor(private moveBehavior: Movable, private flyBehavior?: Flyable) {}
performMove() {
this.moveBehavior.move();
}
performFly() {
if (this.flyBehavior) {
this.flyBehavior.fly();
} else {
console.log("Cannot fly");
}
}
}
const flyingBird = new Bird(new Movable(), new Flyable());
flyingBird.performMove(); // Outputs: Moving
flyingBird.performFly(); // Outputs: Flying
const penguin = new Bird(new Movable());
penguin.performMove(); // Outputs: Moving
penguin.performFly(); // Outputs: Cannot fly
Explanation:
-
Composition:
Bird is composed of behaviors (Movable, Flyable).
- Behaviors can be added or omitted based on the object's needs.
-
Benefits:
- Flexibility in composing objects with different behaviors.
- Avoids issues related to inheritance hierarchies.
- Adheres to Liskov Substitution Principle.
-
Better Design:
- Eliminates unintended behaviors inherited from parent classes.
- Facilitates code reuse through behavior composition.
Conclusion:
Composition provides a more flexible and maintainable approach than inheritance in many cases, leading to better-designed, modular, and reusable code.
Example:
class Builder {
private data: { [key: string]: any } = {};
setName(name: string): this {
this.data.name = name;
return this;
}
setAge(age: number): this {
this.data.age = age;
return this;
}
setAddress(address: string): this {
this.data.address = address;
return this;
}
build(): { [key: string]: any } {
return this.data;
}
}
const builder = new Builder();
const result = builder.setName("Alice").setAge(30).setAddress("123 Main St").build();
console.log(result);
// Outputs: { name: 'Alice', age: 30, address: '123 Main St' }
Benefits:
- Conciseness: Reduces code verbosity by chaining method calls.
- Fluent Interface: Improves readability and expressiveness.
- Immutable Design: Encourages methods that return new instances, promoting immutability (if designed that way).
Implementation Details:
- Returning
this: Methods return this, allowing the next method to be called on the same object.
- Type Annotation
this: Ensures proper type inference when methods are chained.
Use Cases:
- Builders: Construct complex objects step by step.
- Query APIs: Fluent query construction.
- Configuration Objects: Setting options in a chainable manner.
Conclusion:
Method chaining enhances the API's usability, leading to cleaner and more maintainable code in object-oriented designs.
Defining a Namespace:
namespace Utilities {
export function log(message: string) {
console.log(message);
}
export class Helper {
static assist() {
console.log("Assisting...");
}
}
}
Using a Namespace:
Utilities.log("Hello");
Utilities.Helper.assist();
Explanation:
- Declaration: The
namespace keyword defines a namespace.
- Exporting Members: Use
export to make classes, interfaces, functions, etc., accessible outside the namespace.
- Accessing Members: Use the namespace as a qualifier to access exported members.
Benefits:
- Organization: Groups related code together.
- Avoiding Conflicts: Prevents naming conflicts by encapsulating code.
- Modularity: Helps in structuring large codebases logically.
Notes:
- Internal Modules: Namespaces are internal modules; for external modules, it's recommended to use ES modules (import/export).
- Prefer Modules Over Namespaces: In modern TypeScript, modules are preferred for organizing code, especially when using a module loader or bundler.
Conclusion:
Namespaces can help organize code in OOP projects, but with the advent of modules, they're less common in new codebases. Using modules promotes better standards and interoperability.
Example:
class Person {
constructor(private name: string, private age: number) {}
toString(): string {
return `Person [name=${this.name}, age=${this.age}]`;
}
}
const person = new Person("Alice", 30);
console.log(person.toString()); // Outputs: Person [name=Alice, age=30]
console.log(`${person}`); // Outputs: Person [name=Alice, age=30]
Explanation:
-
Overriding toString: The Person class provides its own implementation of toString.
-
String Interpolation: When an object is interpolated in a string, toString is called.
-
Significance:
- Debugging: Provides meaningful information when logging objects.
- Readability: Enhances the understanding of object state when printed.
- Polymorphism: Different classes can provide their own string representations.
Best Practices:
- Ensure that
toString provides concise and useful information.
- Be cautious about including sensitive information in
toString.
Conclusion:
Overriding toString enhances the usability and debuggability of classes in OOP design, allowing for better representation of object instances.
Implementation in TypeScript:
- Define the Handler Interface:
interface Handler {
setNext(handler: Handler): Handler;
handle(request: string): void;
}
- Implement Abstract Handler:
abstract class AbstractHandler implements Handler {
private nextHandler: Handler | null = null;
setNext(handler: Handler): Handler {
this.nextHandler = handler;
return handler;
}
handle(request: string): void {
if (this.nextHandler) {
this.nextHandler.handle(request);
}
}
}
- Implement Concrete Handlers:
class AuthHandler extends AbstractHandler {
handle(request: string): void {
if (request === "AUTH") {
console.log("AuthHandler: Handling authentication.");
} else {
console.log("AuthHandler: Passing to next handler.");
super.handle(request);
}
}
}
class LoggingHandler extends AbstractHandler {
handle(request: string): void {
if (request === "LOG") {
console.log("LoggingHandler: Handling logging.");
} else {
console.log("LoggingHandler: Passing to next handler.");
super.handle(request);
}
}
}
class ErrorHandler extends AbstractHandler {
handle(request: string): void {
console.log("ErrorHandler: Handling error.");
}
}
- Usage Example:
const auth = new AuthHandler();
const logger = new LoggingHandler();
const error = new ErrorHandler();
auth.setNext(logger).setNext(error);
auth.handle("LOG");
// Outputs:
// AuthHandler: Passing to next handler.
// LoggingHandler: Handling logging.
auth.handle("UNKNOWN");
// Outputs:
// AuthHandler: Passing to next handler.
// LoggingHandler: Passing to next handler.
// ErrorHandler: Handling error.
Explanation:
- Chain Setup: Handlers are linked using
setNext.
- Request Handling: Each handler decides whether to handle the request or pass it along.
- Decoupling: The client code sends the request to the chain, not knowing which handler will process it.
- Extensibility: New handlers can be added without modifying existing handlers.
Conclusion:
The Chain of Responsibility pattern promotes loose coupling and flexibility in request processing, adhering to the Open/Closed Principle and enhancing the OOP design.
Example:
abstract class Vehicle {
constructor(protected make: string, protected model: string) {}
abstract startEngine(): void;
info(): void {
console.log(`Vehicle: ${this.make} ${this.model}`);
}
}
class Car extends Vehicle {
startEngine(): void {
console.log(`Starting engine of ${this.make} ${this.model}.`);
}
}
class Motorcycle extends Vehicle {
startEngine(): void {
console.log(`Kickstarting ${this.make} ${this.model}.`);
}
}
const car = new Car("Toyota", "Corolla");
car.startEngine(); // Outputs: Starting engine of Toyota Corolla.
car.info(); // Outputs: Vehicle: Toyota Corolla
const bike = new Motorcycle("Yamaha", "MT-07");
bike.startEngine(); // Outputs: Kickstarting Yamaha MT-07.
bike.info(); // Outputs: Vehicle: Yamaha MT-07
Explanation:
-
Abstract Class Vehicle: Cannot be instantiated directly.
-
Abstract Method startEngine: Must be implemented by subclasses (Car, Motorcycle).
-
Concrete Method info: Available to subclasses without re-implementation.
-
Design Impact:
- Contracts: Forces subclasses to implement specific methods, ensuring a consistent interface.
- Reusability: Provides base functionality while allowing for customization.
- Polymorphism: Subclasses can be treated as instances of the abstract class.
Conclusion:
Using abstract classes and methods enhances class hierarchies by defining templates and contracts for subclasses, promoting better organizational structure and enforceable design patterns in OOP.