Cách Viết Code Comment Bằng Tiếng Anh — Dễ Hiểu, Chuyên Nghiệp
Cách viết code comment bằng tiếng Anh chuyên nghiệp cho developer. Khi nào cần comment, inline comment, block comment, JSDoc, docstring. Bảng từ vựng EN-VN, ví dụ thực tế, lỗi thường gặp và best practices.
Code comment là một trong những kỹ năng viết tiếng Anh developer dùng hàng ngày — nhiều hơn cả email hay meeting. Nhưng rất nhiều developer Việt mắc lỗi:
Comment bằng tiếng Việt (đồng nghiệp quốc tế không đọc được)
Comment dài dòng, thừa thãi (“This function returns true” — ai cũng thấy rồi!)
Comment sai ngữ pháp khiến người đọc hiểu nhầm
Không comment những chỗ thật sự cần giải thích
Bài này hướng dẫn bạn viết code comment bằng tiếng Anh rõ ràng, chuyên nghiệp, đúng ngữ cảnh — kèm bảng từ vựng và ví dụ thực tế.
// ❌ Bad — comment thừa
// Check if user is active
if(user.isActive){...}// ✅ Good — code tự rõ, không cần comment
if(user.isActive){...}
1
2
3
4
5
6
7
# ❌ Bad — diễn tả lại code# Increment counter by 1counter +=1# ✅ Good — giải thích WHY# Reset attempt counter after successful login to prevent lockout carry-overcounter =0
/*
* Calculate the shipping cost based on weight and destination zone.
* Uses tiered pricing: first 5kg at base rate, additional weight at
* reduced rate. International zones add a 15% surcharge.
*/publicdoublecalculateShippingCost(doubleweight,intzone){...}
/**
* Send a password reset email to the user.
*
* @param email - The user's registered email address
* @param locale - Language code for the email template (default: "en")
* @returns A promise that resolves to true if the email was sent successfully
* @throws {UserNotFoundError} If no account matches the email
*
* @example
* await sendPasswordReset("[email protected]", "vi");
*/asyncfunctionsendPasswordReset(email: string,locale?: string):Promise<boolean>{...}
Python (Docstring):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
defcalculate_discount(price:float, tier:str)->float:"""Calculate the discount amount based on the customer's membership tier.
Uses a tiered discount system:
- Silver: 5%
- Gold: 10%
- Platinum: 15%
Args:
price: The original price before discount.
tier: The customer's membership tier ("silver", "gold", or "platinum").
Returns:
The discount amount in the same currency as the input price.
Raises:
ValueError: If the tier is not recognized.
"""
// TODO: Migrate to WebSocket for real-time updates (tracking: JIRA-1234)
// FIXME: Race condition when two users submit at the same time
// HACK: Workaround for Chrome 120 flexbox rendering bug
// NOTE: This endpoint is deprecated — use /v2/users instead
// WARNING: Do not change the order of these operations — it will break idempotency
// Returns the user's full name// → Nhưng function đã đổi sang return nickname 3 tháng trước!publicStringgetDisplayName(){returnuser.getNickname();// Comment nói "full name" nhưng code trả về nickname}
⚠️ A wrong comment is worse than no comment. Comment sai còn nguy hiểm hơn không có comment.
// ❌ Too much
// This function is used to validate the email address that the user
// enters into the registration form on the signup page. It checks
// whether the email contains an @ symbol and a valid domain name
// using a regular expression pattern.
functionvalidateEmail(email){...}// ✅ Just right
// Validate email format using RFC 5322 simplified regex
functionvalidateEmail(email){...}
Các comment sau đây có vấn đề. Hãy viết lại cho đúng:
1
2
3
4
5
6
7
8
9
10
11
// 1. Comment thừa
// Add 1 to count
count++;// 2. Comment tiếng Việt
// Lấy danh sách user từ database
constusers=awaitdb.query("SELECT * FROM users");// 3. Comment mơ hồ
// Fix the thing
if(data.length===0)return[];
💡 Gợi ý đáp án
1
2
3
4
5
6
7
8
9
10
// 1. Xóa comment (code đã tự rõ ràng)
count++;// 2. Viết bằng tiếng Anh, giải thích WHY nếu cần
// Fetch all users — no pagination needed, max 100 records per org
constusers=awaitdb.query("SELECT * FROM users");// 3. Giải thích context cụ thể
// Return early for empty datasets to avoid division by zero in chart rendering
if(data.length===0)return[];
defretry(func, max_attempts=3, delay=1):"""Retry a function with exponential backoff.
Calls the given function up to max_attempts times. On failure,
waits with exponential backoff (delay * 2^attempt) before retrying.
Raises the last exception if all attempts fail.
Args:
func: A callable with no arguments to execute.
max_attempts: Maximum number of retry attempts (default: 3).
delay: Base delay in seconds between retries (default: 1).
Raises:
Exception: The last exception raised by func after all retries.
"""for attempt inrange(max_attempts):try:return func()except Exception:if attempt == max_attempts -1:raise# Exponential backoff: 1s, 2s, 4s, ... time.sleep(delay *(2** attempt))
// Kiểm tra xem token có hết hạn chưa, nếu hết hạn thì refresh// Cần refresh trước 5 phút để tránh bị lỗi giữa chừngif(token.expiresAt<now+300){token=refreshToken(token);}
💡 Gợi ý đáp án
1
2
3
4
5
// Proactively refresh token 5 minutes before expiry to prevent// mid-request failures caused by token expiration during processingif(token.expiresAt<now+300){token=refreshToken(token);}