Chuyển tới nội dung chính

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
Mục tiêu cuối cùng

đọ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 Stylecách viết ký tự (camelCase, snake_case, PascalCase)
Naming Semanticscấu trúc ngữ nghĩa của tên

Ví dụ:

openFile
  • camelCase → style
  • Verb + 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ầnVai trò
Verbhành động
Nounobject/dữ liệu
Adjectivetrạng thái/tính chất
Prefix logictrạng thái logic (is, has, can)
Context wordngữ 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
Nounobject đơn giản
Adjective + Nounobject có trạng thái/tính chất
Noun + Noundomain 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

PrefixOwnership semantics
ownedsở hữu độc quyền
sharedshared ownership
weakweak reference
borrowedkhô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ầnVai trò
Verbhành động
Nounobject 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
createtạo object đầy đủ
makeutility/simple construction
buildtạo từng bước
generatesinh dữ liệu

5.6 Conversion Function

Pattern

to + Noun

as + Noun

from + Noun

Ví dụ

toString()
toJson()
asView()
fromBytes()

Semantics

PrefixÝ nghĩa
totạo representation mới
aslightweight view/cast
fromkhở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
oncallback/event slot
handlexử 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
validatekiểm tra hợp lệ logic
checkkiểm tra tổng quát
verifyxá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
findtìm object cụ thể
searchtìm tập kết quả
querytruy 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ả

FunctionResponsibility
onAddTabRequestedUI event
configureSyntaxHighlightingForTabbusiness 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 + Nounaction
Adjective + Nounstate/property
Noun + Noundomain object
is + Adjectivebool state
has + Nounownership/existence
can + Verbcapability
set + Nounsetter
create/make/build + Nounobject creation
to/as/from + Nounconversion
handle/on + Eventevent handling
current/next/previous + Nountemporal state
max/min/default + Nounconfig/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ó.