Files
pos-system/docs/vi/skills/comment-code.md
Ho Ngoc Hai 9b6c585f57 Enhance documentation structure and improve bilingual support across skills
- Updated skill documentation files to include structured metadata for better organization.
- Enhanced bilingual descriptions and guidelines for clarity in both English and Vietnamese.
- Refined sections on usage, best practices, and related skills to ensure consistency across all documentation.
- Improved formatting and removed outdated references to streamline the documentation experience.
- Added best practices checklists to relevant skills for better usability and adherence to standards.
2026-01-01 07:35:44 +07:00

20 KiB

Viết Comment Code

Guidelines for adding comprehensive bilingual code comments (English and Vietnamese) to improve code readability for international and Vietnamese teams.

Hướng dẫn thêm comments song ngữ (tiếng Anh và tiếng Việt) để cải thiện khả năng đọc code cho các đội quốc tế và Việt Nam.

Tổng Quan

Code comments are essential for maintaining and understanding codebase, especially in a bilingual development environment. This guide provides comprehensive patterns for writing clear, consistent, and helpful comments in both English and Vietnamese across the GoodGo microservices platform. It covers JSDoc documentation, inline comments, special comment types, and best practices for effective code documentation.

Comments code là điều cần thiết để bảo trì và hiểu codebase, đặc biệt trong môi trường phát triển song ngữ. Hướng dẫn này cung cấp các patterns toàn diện để viết comments rõ ràng, nhất quán và hữu ích bằng cả tiếng Anh và tiếng Việt trên nền tảng microservices GoodGo. Nó bao gồm tài liệu JSDoc, inline comments, các loại comment đặc biệt, và best practices cho tài liệu code hiệu quả.

Khi Nào Sử Dụng

Use bilingual commenting patterns when:

  • Adding comments to new code
  • Documenting existing code
  • Creating JSDoc/TSDoc documentation
  • Writing function/class descriptions
  • Explaining complex logic or algorithms
  • Adding inline comments for clarification
  • Documenting API endpoints and interfaces
  • Explaining configuration and setup code
  • Writing security-critical code documentation
  • Creating error handling documentation

Sử dụng các patterns comment song ngữ khi:

  • Thêm comments vào code mới
  • Tài liệu hóa code hiện có
  • Tạo tài liệu JSDoc/TSDoc
  • Viết mô tả functions/classes
  • Giải thích logic hoặc thuật toán phức tạp
  • Thêm inline comments để làm rõ
  • Tài liệu hóa API endpoints và interfaces
  • Giải thích code cấu hình và setup
  • Viết tài liệu code bảo mật quan trọng
  • Tạo tài liệu xử lý lỗi

Khái Niệm Chính

Định Dạng Comment

All comments in the GoodGo project should be bilingual, with English (EN) followed by Vietnamese (VI) translations.

Pattern / Mẫu:

[English explanation]
// VI: [Vietnamese explanation]

Các Loại Comment

  1. Single-line Comments (//) / Comments Một Dòng: For brief explanations / Cho giải thích ngắn gọn
  2. Multi-line Comments (/* */) / Comments Nhiều Dòng: For longer explanations / Cho giải thích dài hơn
  3. JSDoc Comments (/** */) / Comments JSDoc: For function, class, and API documentation / Cho tài liệu function, class và API
  4. Prisma Comments (///) / Comments Prisma: For database schema documentation / Cho tài liệu schema database

Các Pattern Thường Dùng

Comments Một Dòng

Use single-line comments for brief explanations of code behavior / Sử dụng single-line comments cho giải thích ngắn gọn về hành vi code.

Initialize database connection
// VI: Khởi tạo kết nối database
const db = await createConnection();

Enable detailed logging in development, minimal in production
// VI: Bật ghi log chi tiết trong development, tối thiểu trong production
'error';

Real Example / Ví dụ Thực tế: services/iam-service/src/config/database.config.ts

Comments Nhiều Dòng

Use multi-line comments for detailed explanations or step-by-step processes / Sử dụng multi-line comments cho giải thích chi tiết hoặc quy trình từng bước.

/**
Validates user credentials and returns JWT token
 * VI: Xác thực thông tin đăng nhập và trả về JWT token
 * 
 * @param email - User email address / Địa chỉ email người dùng
 * @param password - User password / Mật khẩu người dùng
 * @returns JWT token / Mã JWT token
 * @throws AuthenticationError if credentials invalid / Lỗi xác thực nếu thông tin không hợp lệ
 */
async function login(email: string, password: string): Promise<string> {
Implementation here
  // VI: Implementation ở đây
}

Tài Liệu Function

Use JSDoc format for all public functions with bilingual descriptions / Sử dụng format JSDoc cho tất cả public functions với mô tả song ngữ.

/**
Calculates the total price including tax and discount
 * VI: Tính tổng giá bao gồm thuế và giảm giá
 * 
 * @param basePrice - Original price / Giá gốc
 * @param taxRate - Tax rate (0-1) / Tỷ lệ thuế (0-1)
 * @param discount - Discount amount / Số tiền giảm giá
 * @returns Final price / Giá cuối cùng
 */
function calculateTotal(
  basePrice: number,
  taxRate: number,
  discount: number
): number {
Apply discount first
  // VI: Áp dụng giảm giá trước
  const discountedPrice = basePrice - discount;
  
Then calculate tax
  // VI: Sau đó tính thuế
  const tax = discountedPrice * taxRate;
  
  return discountedPrice + tax;
}

Real Example / Ví dụ Thực tế: services/iam-service/src/modules/feature/feature.service.ts

Tài Liệu Class

Document classes with bilingual descriptions and explain their purpose / Tài liệu hóa classes với mô tả song ngữ và giải thích mục đích của chúng.

/**
Service for managing features in the system
 * VI: Service để quản lý các features trong hệ thống
 */
export class FeatureService {
  /**
Create a new feature
   * VI: Tạo một feature mới
   * 
   * @param data - Feature data / Dữ liệu feature
   * @returns Created feature / Feature đã tạo
   */
  async create(data: { name: string; title?: string }) {
    // Implementation
  }
}

Real Example / Ví dụ Thực tế: services/iam-service/src/modules/feature/feature.service.ts

Tài Liệu Interface/Type

Document interfaces and types to explain their structure and purpose / Tài liệu hóa interfaces và types để giải thích cấu trúc và mục đích của chúng.

/**
User data transfer object
 * VI: Đối tượng truyền dữ liệu người dùng
 */
interface UserDto {
Unique user identifier / VI:  định danh duy nhất */
  id: string;
  
User email address / VI: Địa chỉ email người dùng */
  email: string;
  
User display name / VI: Tên hiển thị người dùng */
  name: string;
  
User role for authorization / VI: Vai trò người dùng để phân quyền */
  role: 'admin' | 'user' | 'guest';
}

Comments Cấu Hình

Document configuration files and environment variables with clear explanations / Tài liệu hóa file cấu hình và biến môi trường với giải thích rõ ràng.

/**
Prisma client instance configured for the application
 * VI: Instance Prisma client được cấu hình cho ứng dụng
 */
export const prisma = new PrismaClient({
Enable detailed logging in development, minimal in production
  // VI: Bật ghi log chi tiết trong development, tối thiểu trong production
['error'],
});

/**
Establish database connection on application startup
 * VI: Thiết lập kết nối database khi khởi động ứng dụng
 */
export const connectDatabase = async (): Promise<void> => {
  try {
Connect to database using Prisma
    // VI: Kết nối tới database sử dụng Prisma
    await prisma.$connect();
    logger.info('Database connected successfully / Kết nối database thành công');
  } catch (error) {
Log error and exit if database connection fails
    // VI: Ghi log lỗi và thoát nếu kết nối database thất bại
    logger.error('Database connection failed / Kết nối database thất bại', { error });
    process.exit(1);
  }
};

Real Example / Ví dụ Thực tế: services/iam-service/src/config/database.config.ts

Tài Liệu Middleware

Document middleware functions with their purpose and behavior / Tài liệu hóa middleware functions với mục đích và hành vi của chúng.

/**
Authentication middleware to verify JWT tokens
 * VI: Middleware xác thực để kiểm tra JWT token
 */
export function authMiddleware(
  req: Request,
  res: Response,
  next: NextFunction
) {
Extract token from Authorization header
  // VI: Lấy token từ header Authorization
  const authHeader = req.headers.authorization;
  const token = authHeader?.replace('Bearer ', '');

  if (!token) {
    return res.status(401).json({
      success: false,
      error: {
        code: 'NO_TOKEN',
        message: 'Authentication required / Yêu cầu xác thực',
      },
    });
  }

  try {
Verify token and extract payload
    // VI: Xác minh token và lấy payload
    const payload = jwt.verify(token, JWT_SECRET);
    req.user = payload;
    next();
  } catch (error) {
    return res.status(401).json({
      success: false,
      error: {
        code: 'INVALID_TOKEN',
        message: 'Invalid or expired token / Token không hợp lệ hoặc hết hạn',
      },
    });
  }
}

Comments Schema Prisma

Use triple-slash comments (///) for Prisma schema documentation / Sử dụng triple-slash comments (///) cho tài liệu Prisma schema.

User model for authentication and profile
/// VI: Model người dùng cho xác thực và hồ sơ
model User {
Unique identifier / VI: Mã định danh duy nhất
  id        String   @id @default(cuid())
  
User email (unique) / VI: Email người dùng (duy nhất)
  email     String   @unique
  
Hashed password / VI: Mật khẩu đã mã hóa
  password  String
  
Display name / VI: Tên hiển thị
  name      String
  
Account creation timestamp / VI: Thời gian tạo tài khoản
  createdAt DateTime @default(now())
  
Last update timestamp / VI: Thời gian cập nhật cuối
  updatedAt DateTime @updatedAt

  @@map("users")
}

Comments Test

Document test setup and explain test scenarios in both languages / Tài liệu hóa test setup và giải thích test scenarios bằng cả hai ngôn ngữ.

Mock environment variables for tests
// VI: Mock biến môi trường cho tests
process.env.NODE_ENV = 'test';
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test_db';

Mock external services to avoid real network calls
// VI: Mock các service bên ngoài để tránh gọi mạng thật
jest.mock('@goodgo/logger', () => ({
  logger: {
    info: jest.fn(),
    error: jest.fn(),
  },
}));

describe('FeatureService', () => {
  it('should create a feature successfully', async () => {
Arrange
    // VI: Chuẩn bị
    const testData = { name: 'test-feature' };
    
Act
    // VI: Thực hiện
    const result = await service.create(testData);
    
Assert
    // VI: Kiểm tra
    expect(result).toBeDefined();
  });
});

Real Example / Ví dụ Thực tế: services/iam-service/src/__tests__/setupTests.ts

Comments Logic Phức Tạp

When explaining complex algorithms or business logic, break it down into steps / Khi giải thích thuật toán phức tạp hoặc logic nghiệp vụ, chia nhỏ thành các bước.

Step 1: Validate input parameters
// VI: Bước 1: Xác thực tham số đầu vào
if (!email || !password) {
  throw new ValidationError('Email and password required');
}

Step 2: Check if user exists in database
// VI: Bước 2: Kiểm tra xem người dùng có tồn tại trong database
const user = await prisma.user.findUnique({ where: { email } });
if (!user) {
  throw new NotFoundError('User not found');
}

Step 3: Verify password hash
// VI: Bước 3: Xác minh hash mật khẩu
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
  throw new AuthenticationError('Invalid credentials');
}

Step 4: Generate and return JWT token
// VI: Bước 4: Tạo và trả về JWT token
const token = jwt.sign({ userId: user.id }, JWT_SECRET);
return { token, user };

Các Loại Comment Đặc Biệt

Comments TODO

Use TODO comments for future improvements with bilingual descriptions / Sử dụng TODO comments cho cải tiến trong tương lai với mô tả song ngữ.

Implement caching for better performance
// TODO VI: Triển khai caching để cải thiện hiệu suất

Add rate limiting to prevent abuse
// TODO VI: Thêm rate limiting để ngăn chặn lạm dụng

Comments FIXME

Use FIXME comments for code that needs fixing / Sử dụng FIXME comments cho code cần sửa.

This causes memory leak, needs refactoring
// FIXME VI: Đoạn này gây rò rỉ bộ nhớ, cần refactor

Temporary workaround, should implement proper solution
// FIXME VI: Giải pháp tạm thời, nên triển khai giải pháp đúng đắn

Comments CẢNH BÁO

Use WARNING comments for code that requires special attention / Sử dụng WARNING comments cho code cần chú ý đặc biệt.

Do not modify this without updating the database schema
// WARNING VI: Không sửa đổi phần này mà không cập nhật schema database

This function modifies global state, use with caution
// WARNING VI: Function này thay đổi global state, sử dụng cẩn thận

Comments GHI CHÚ

Use NOTE comments for important information or explanations / Sử dụng NOTE comments cho thông tin hoặc giải thích quan trọng.

This is intentionally async to avoid blocking the event loop
// NOTE VI: Đây là async có chủ ý để tránh block event loop

Priority: Docker Compose > .env.local > .env > System environment
// NOTE VI: Ưu tiên: Docker Compose > .env.local > .env > Môi trường hệ thống

Thực Hành Tốt Nhất

Vị Trí Comment

  • Place bilingual comments together (EN first, then VI) / Đặt comments song ngữ cùng nhau (EN trước, sau đó VI)
  • Keep comments close to the code they describe / Giữ comments gần với code mà chúng mô tả
  • Use JSDoc format for functions and classes / Sử dụng format JSDoc cho functions và classes
  • Update comments when code changes / Cập nhật comments khi code thay đổi

Nội Dung Comment

  • DO: Explain WHY, not WHAT (code shows what) / Giải thích TẠI SAO, không phải CÁI GÌ
  • DO: Document complex logic and business rules / Tài liệu hóa logic phức tạp và quy tắc nghiệp vụ
  • DO: Include parameter descriptions and return types / Bao gồm mô tả tham số và kiểu trả về
  • DO: Document error conditions and exceptions / Tài liệu hóa điều kiện lỗi và ngoại lệ
  • DON'T: State the obvious / Không nói điều hiển nhiên
  • DON'T: Write redundant comments / Không viết comments thừa
  • DON'T: Comment out code (use version control instead) / Không comment code (sử dụng version control)

Hướng Dẫn Ngôn Ngữ

English / Tiếng Anh:

  • Use clear, concise technical English / Sử dụng tiếng Anh kỹ thuật rõ ràng, ngắn gọn
  • Use proper technical terminology / Sử dụng thuật ngữ kỹ thuật đúng
  • Be specific and actionable / Cụ thể và có thể thực hiện

Vietnamese / Tiếng Việt:

  • Use proper Vietnamese technical terms / Sử dụng thuật ngữ kỹ thuật tiếng Việt đúng
  • Keep translations accurate and natural / Giữ bản dịch chính xác và tự nhiên
  • Use consistent terminology across codebase / Sử dụng thuật ngữ nhất quán trên codebase
  • Prefer technical Vietnamese terms over literal translations / Ưu tiên thuật ngữ kỹ thuật Việt hơn dịch theo nghĩa đen

Ưu Tiên Tài Liệu

High Priority (Always document / Luôn tài liệu hóa):

  • Public APIs and exported functions / API công khai và functions được export
  • Complex algorithms and business logic / Thuật toán phức tạp và logic nghiệp vụ
  • Security-critical code / Code bảo mật quan trọng
  • Configuration and environment setup / Cấu hình và thiết lập môi trường
  • Error handling strategies / Chiến lược xử lý lỗi

Medium Priority (Document when helpful / Tài liệu khi hữu ích):

  • Helper functions with non-obvious behavior / Helper functions có hành vi không rõ ràng
  • Data transformations / Chuyển đổi dữ liệu
  • Integration points with external services / Điểm tích hợp với services bên ngoài

Low Priority (Optional / Tùy chọn):

  • Simple getters/setters / Getters/setters đơn giản
  • Self-explanatory code / Code tự giải thích
  • Standard CRUD operations / Các thao tác CRUD tiêu chuẩn

Ví Dụ Từ Dự Án

Ví Dụ Comment Thực Tế

  1. Service Comments: services/iam-service/src/modules/feature/feature.service.ts
  2. Config Comments: services/iam-service/src/config/database.config.ts
  3. Test Comments: services/iam-service/src/__tests__/setupTests.ts
  4. Jest Config Comments: services/iam-service/jest.config.ts

Patterns Comment Trong Các Ngữ Cảnh Khác Nhau

  • Controllers: Document API endpoints and request/response handling / Tài liệu hóa API endpoints và xử lý request/response
  • Services: Document business logic and data processing / Tài liệu hóa logic nghiệp vụ và xử lý dữ liệu
  • Middleware: Document authentication, authorization, and request processing / Tài liệu hóa xác thực, phân quyền và xử lý request
  • Repositories: Document database operations and query logic / Tài liệu hóa các thao tác database và logic query
  • Config Files: Document configuration options and environment variables / Tài liệu hóa tùy chọn cấu hình và biến môi trường
  • Tests: Document test scenarios and setup procedures / Tài liệu hóa test scenarios và quy trình setup

Tham Khảo Nhanh

Template Comment Function

/**
[Brief description in English]
 * VI: [Mô tả ngắn gọn bằng tiếng Việt]
 * 
 * @param paramName - EN description / VI mô tả
 * @returns EN description / VI mô tả
 * @throws ErrorType EN when / VI khi nào
 */

Template Inline Comment

[English explanation]
// VI: [Giải thích tiếng Việt]

Template Block Phức Tạp

Step N: [What this block does]
// VI: Bước N: [Block này làm gì]

Template Comment Class

/**
[Class purpose in English]
 * VI: [Mục đích class bằng tiếng Việt]
 */
export class ClassName {
  /**
[Property description]
   * VI: [Mô tả property]
   */
  private property: string;
}

Template Comment Interface

/**
[Interface purpose in English]
 * VI: [Mục đích interface bằng tiếng Việt]
 */
interface InterfaceName {
Property description / VI:  tả property */
  property: string;
}

Skills Liên Quan

  • Testing Patterns: Writing comments in test files / Viết comments trong file test
  • API Design: Documenting API endpoints / Tài liệu hóa API endpoints
  • Documentation: Writing technical documentation / Viết tài liệu kỹ thuật
  • Project Rules: Code organization and standards / Tổ chức code và tiêu chuẩn

Tài Nguyên

Tiêu Chuẩn Tài Liệu

Tài Liệu Nội Bộ

Công Cụ

  • JSDoc: Generate API documentation from comments / Tạo tài liệu API từ comments
  • ESLint: Enforce comment style and completeness / Thực thi style và tính đầy đủ của comments
  • Prettier: Format comments consistently / Định dạng comments nhất quán
  • VS Code: IntelliSense uses JSDoc comments for better autocomplete / IntelliSense sử dụng JSDoc comments cho autocomplete tốt hơn