Pattern đặt tên theo ngữ nghĩa của biến và hàm trong C++
1. Mục tiêu thật sự của việc đặt tên
Trong lập trình hiện đại, đặc biệt với C++, tên không chỉ dùng để “phân biệt identifier”.
Tên có nhiệm vụ:
- truyền đạt ý định (intent)
- mô tả vai trò logic
- mô tả trách nhiệm
- mô tả trạng thái
- giảm nhu cầu đọc implementation
đọc tên là hiểu object hoặc function đó đại diện cho điều gì và làm gì.
2. Hai khái niệm cần tách biệt
| Khái niệm | Ý nghĩa |
|---|---|
| Naming Style | cách viết ký tự (camelCase, snake_case, PascalCase) |
| Naming Semantics | cấu trúc ngữ nghĩa của tên |
Ví dụ:
openFile
camelCase→ styleVerb + Noun→ semantics
Bài viết này tập trung vào semantics.
3. Thành phần ngữ nghĩa cơ bản
Tên trong code thường được cấu thành từ:
| Thành phần | Vai trò |
|---|---|
| Verb | hành động |
| Noun | object/dữ liệu |
| Adjective | trạng thái/tính chất |
| Prefix logic | trạng thái logic (is, has, can) |
| Context word | ngữ cảnh (current, pending, default) |
4. Pattern đặt tên cho variable
4.1 Variable thông thường
Pattern phổ biến
Noun
hoặc
Adjective + Noun
hoặc
Noun + Noun
Ví dụ
user
file
buffer
currentIndex
maxBufferSize
activeConnection
filePath
userName
errorMessage
Ý nghĩa
| Pattern | Ý nghĩa |
|---|---|
| Noun | object đơn giản |
| Adjective + Noun | object có trạng thái/tính chất |
| Noun + Noun | domain object cụ thể |
4.2 Bool Variable
Bool phải đọc được như một câu logic.
Pattern chuẩn
is + Adjective
has + Noun
can + Verb
should + Verb
was + VerbPast
Ví dụ
isOpen
isVisible
isEnabled
hasValue
hasChildren
hasPermission
canRead
canWrite
canExecute
shouldClose
shouldReload
wasLoaded
wasInitialized
Vì sao pattern này quan trọng?
Đọc tự nhiên:
if (isOpen)
thay vì:
if (open)
4.3 Container Variable
Container nên biểu diễn “tập hợp”.
Pattern
Plural Noun
Ví dụ
users
files
tasks
connections
windows
Sai phổ biến
userVector
taskList
fileArray
Tên không nên phụ thuộc implementation detail.
4.4 Variable biểu diễn ownership
Đặc biệt quan trọng trong C++.
Pattern
owned + Noun
shared + Noun
weak + Noun
borrowed + Noun
Ví dụ
ownedBuffer
sharedConfig
weakSession
borrowedView
Ý nghĩa
| Prefix | Ownership semantics |
|---|---|
| owned | sở hữu độc quyền |
| shared | shared ownership |
| weak | weak reference |
| borrowed | không sở hữu |
4.5 Variable trạng thái thời gian
Pattern
current + Noun
next + Noun
previous + Noun
pending + Noun
Ví dụ
currentState
nextFrame
previousNode
pendingRequest
4.6 Constant / Config Variable
Pattern
max + Noun
min + Noun
default + Noun
Ví dụ
maxBufferSize
minValue
defaultTimeout
5. Pattern đặt tên cho Function
Function gần như luôn đại diện cho “action”.
5.1 Function thông thường
Pattern chuẩn
Verb + Noun
Ví dụ
openFile()
closeConnection()
loadTexture()
parseConfig()
Ý nghĩa
| Thành phần | Vai trò |
|---|---|
| Verb | hành động |
| Noun | object bị tác động |
5.2 Getter Function
Getter trong C++ hiện đại thường mang semantics của property.
Pattern
Noun
hoặc
Adjective + Noun
Ví dụ
size()
data()
name()
filePath()
bufferSize()
Không nên
getSize()
getName()
trừ khi codebase dùng convention kiểu Java/C#.
5.3 Setter Function
Pattern
set + Noun
Ví dụ
setName()
setFilePath()
setBufferSize()
5.4 Bool Function
Bool function phải đọc như một câu hỏi logic.
Pattern
is + Adjective
has + Noun
can + Verb
should + Verb
contains + Noun
Ví dụ
isOpen()
hasValue()
canRead()
containsKey()
shouldReload()
5.5 Factory Function
Factory function biểu diễn việc tạo object.
Pattern
create + Noun
make + Noun
build + Noun
generate + Noun
Ví dụ
createWindow()
makeRequest()
buildPipeline()
generateToken()
Khác biệt semantics
| Verb | Ý nghĩa |
|---|---|
| create | tạo object đầy đủ |
| make | utility/simple construction |
| build | tạo từng bước |
| generate | sinh dữ liệu |
5.6 Conversion Function
Pattern
to + Noun
as + Noun
from + Noun
Ví dụ
toString()
toJson()
asView()
fromBytes()
Semantics
| Prefix | Ý nghĩa |
|---|---|
| to | tạo representation mới |
| as | lightweight view/cast |
| from | khởi tạo từ nguồn |
5.7 Mutation Function
Function thay đổi state.
Pattern
Verb
hoặc
Verb + Noun
Ví dụ
clear()
reset()
resize()
appendData()
removeUser()
5.8 Event Handler Function
Rất phổ biến trong GUI / async / event-driven architecture.
Pattern
handle + Event
on + Event
Ví dụ
handleMouseClick()
handleConnectionClosed()
onButtonPressed()
onTabClosed()
Khác biệt semantics
| Prefix | Ý nghĩa |
|---|---|
| on | callback/event slot |
| handle | xử lý event |
5.9 Async / Thread / Task Function
Pattern
start + Noun
stop + Noun
waitFor + Noun
Ví dụ
startWorker()
stopThread()
waitForCompletion()
5.10 Validation Function
Pattern
validate + Noun
check + Noun
verify + Noun
Ví dụ
validateConfig()
checkPermission()
verifyChecksum()
Khác biệt semantics
| Verb | Ý nghĩa |
|---|---|
| validate | kiểm tra hợp lệ logic |
| check | kiểm tra tổng quát |
| verify | xác minh tính đúng đắn |
5.11 Search / Query Function
Pattern
find + Noun
search + Noun
query + Noun
Ví dụ
findUser()
searchFiles()
queryDatabase()
Semantics
| Verb | Ý nghĩa |
|---|---|
| find | tìm object cụ thể |
| search | tìm tập kết quả |
| query | truy vấn dữ liệu |
6. Pattern cho function context phức tạp
Đây là nơi nhiều codebase bắt đầu đặt tên sai.
6.1 Sai phổ biến
Nhồi toàn bộ context vào tên:
handleSyntaxHighlightingFromAddTabRequested()
Vấn đề
Tên đang encode:
- subsystem
- event source
- event state
- action
vào một chuỗi tuyến tính.
6.2 Root cause
Thường do:
- abstraction chưa rõ
- function responsibility chưa tách
- event coupling quá mạnh
6.3 Hướng tốt hơn
Tách:
- event handling
- business logic
Ví dụ
void MainWindow::onAddTabRequested()
{
configureSyntaxHighlightingForTab();
}
Kết quả
| Function | Responsibility |
|---|---|
| onAddTabRequested | UI event |
| configureSyntaxHighlightingForTab | business operation |
7. Quy tắc ngữ nghĩa quan trọng nhất
7.1 Tên phải phản ánh intent, không phản ánh implementation
Sai
sortVector()
Đúng
sortUsers()
7.2 Tên phải phản ánh cost nếu operation nặng
Sai
data()
nhưng bên trong:
- đọc file
- parse JSON
- query DB
Đúng
loadData()
fetchData()
parseData()
7.3 Tránh meaningless words
Sai
data
value
info
temp
object
manager
helper
7.4 Tránh dư thừa context
Sai
class User {
std::string m_userName;
};
Đúng
class User {
std::string m_name;
};
8. Tổng hợp pattern quan trọng nhất
| Pattern | Ý nghĩa |
|---|---|
| Verb + Noun | action |
| Adjective + Noun | state/property |
| Noun + Noun | domain object |
| is + Adjective | bool state |
| has + Noun | ownership/existence |
| can + Verb | capability |
| set + Noun | setter |
| create/make/build + Noun | object creation |
| to/as/from + Noun | conversion |
| handle/on + Event | event handling |
| current/next/previous + Noun | temporal state |
| max/min/default + Noun | config/limit |
9. Kết luận
Đặt tên theo ngữ nghĩa trong C++ hiện đại không phải là:
“đặt sao cho đẹp”
mà là:
encode đúng intent, responsibility và abstraction level.
Một tên tốt phải giúp:
- đọc nhanh
- hiểu logic
- giảm nhu cầu đọc implementation
- giảm ambiguity
- giảm cognitive load
Mục tiêu cuối cùng:
code tự mô tả hành vi của chính nó.