Lập trình hướng đối tượng (OOP) trong NestJS

2 min read



OOP là gì?

OOP (Object-Oriented Programming) là lập trình hướng đối tượng — một phương pháp lập trình tổ chức chương trình dưới dạng các object (đối tượng) và class (lớp).

Mục tiêu của OOP:

  • Tái sử dụng code
  • Dễ bảo trì
  • Dễ mở rộng
  • Tổ chức chương trình rõ ràng hơn

NestJS sử dụng rất mạnh tư duy OOP nhờ được xây dựng bằng TypeScript.


4 tính chất chính của OOP trong NestJS

1. Encapsulation (Đóng gói)

Encapsulation là việc gom dữ liệu và phương thức xử lý dữ liệu vào cùng một class, đồng thời hạn chế truy cập trực tiếp từ bên ngoài.

Ví dụ:

export class UserService {
  private users = ['David', 'John'];

  getUsers() {
    return this.users;
  }
}

Ở đây:

  • users được đặt là private
  • Chỉ có thể truy cập thông qua getUsers()

Lợi ích:

  • Bảo vệ dữ liệu
  • Giảm lỗi ngoài ý muốn

2. Inheritance (Kế thừa)

Inheritance cho phép class con sử dụng lại thuộc tính và phương thức của class cha.

Ví dụ:

export class BaseService {
  log(message: string) {
    console.log(message);
  }
}
export class UserService extends BaseService {
  getUsers() {
    this.log('Get users');
    return [];
  }
}

UserService kế thừa BaseService nên có thể dùng log().

Ứng dụng trong NestJS:

  • BaseService
  • BaseController
  • Common Exception Handling

3. Polymorphism (Đa hình)

Polymorphism cho phép nhiều class có cùng method nhưng xử lý khác nhau.

Ví dụ:

class Animal {
  sound() {
    console.log('Animal sound');
  }
}
class Dog extends Animal {
  sound() {
    console.log('Woof');
  }
}
class Cat extends Animal {
  sound() {
    console.log('Meow');
  }
}

Khi gọi sound():

  • Dog → “Woof”
  • Cat → “Meow”

Trong NestJS:

  • Strategy Pattern
  • Guard
  • Interceptor
  • Custom Provider

4. Abstraction (Trừu tượng)

Abstraction giúp ẩn đi logic phức tạp và chỉ cung cấp phần cần thiết.

Ví dụ abstract class:

abstract class DatabaseService {
  abstract connect(): void;
}
class MySQLService extends DatabaseService {
  connect(): void {
    console.log('Connected MySQL');
  }
}

Lợi ích:

  • Chuẩn hóa cấu trúc
  • Dễ thay đổi implementation

OOP trong cấu trúc NestJS

Controller là Object

@Controller('users')
export class UsersController {}

UsersController thực chất là một class.


Service là Object

@Injectable()
export class UsersService {}

NestJS quản lý object này thông qua Dependency Injection.


Dependency Injection và OOP

Ví dụ:

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}
}

Ở đây:

  • UsersController không tự tạo UsersService
  • NestJS inject object vào constructor

Điều này giúp:

  • Loose coupling
  • Dễ test
  • Dễ maintain

Access Modifier trong OOP

public

Có thể truy cập mọi nơi.

public name: string;

private

Chỉ truy cập trong class.

private password: string;

protected

Class con có thể truy cập.

protected users: [];

Interface trong NestJS

Interface giúp định nghĩa cấu trúc object.

Ví dụ:

interface User {
  id: number;
  name: string;
}

Dùng nhiều trong:

  • DTO
  • Response type
  • Repository pattern

Ví dụ OOP hoàn chỉnh trong NestJS

User Service

@Injectable()
export class UsersService {
  private users = [];

  create(user: any) {
    this.users.push(user);
  }

  findAll() {
    return this.users;
  }
}

User Controller

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() body: any) {
    this.usersService.create(body);
  }

  @Get()
  getUsers() {
    return this.usersService.findAll();
  }
}

Trong ví dụ này có:

  • Encapsulation
  • Object
  • Dependency Injection
  • Class
  • Method

Vì sao NestJS phù hợp với OOP?

1. Dùng TypeScript

TypeScript hỗ trợ:

  • Class
  • Interface
  • Abstract class
  • Access modifier

2. Kiến trúc rõ ràng

NestJS chia:

  • Controller
  • Service
  • Module
  • Provider

Rất giống mô hình OOP trong enterprise.


3. Dependency Injection mạnh

DI là một phần rất quan trọng trong OOP hiện đại.


Kết luận

NestJS là framework backend áp dụng tư duy OOP rất mạnh thông qua:

  • Class
  • Interface
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Dependency Injection

Nhờ vậy, NestJS đặc biệt phù hợp cho các hệ thống lớn cần:

  • Clean Architecture
  • Maintainability
  • Scalability
  • Reusability

Avatar photo

Leave a Reply

Your email address will not be published. Required fields are marked *