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

1. Mục tiêu thật sự của việc đặt tên

Trong C++ hiện đại, tên không chỉ dùng để phân biệt identifier.

Tên còn phải truyền đạt:

  • intent (ý định)
  • responsibility (trách nhiệm)
  • abstraction level (mức trừu tượng)
  • state (trạng thái)
  • relationship (quan hệ logic)

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à đang làm gì.

Một tên tốt giúp:

  • giảm nhu cầu đọc implementation
  • giảm ambiguity
  • giảm cognitive load
  • tăng khả năng maintain
  • tăng khả năng đọc code theo ngữ cảnh

2. Cần phân biệt: Naming Style và Naming Semantics

Naming Style​

Là cách viết ký tự.

Ví dụ:

StyleVí dụ
camelCaseopenFile
snake_caseopen_file
PascalCaseOpenFile

Đây chỉ là hình thức trình bày.


Naming Semantics​

Là cấu trúc ngữ nghĩa của tên.

Ví dụ:

openFile

Trong đó:

Thành phầnVai trò
openaction/verb
filetarget/noun

Tức là:

Verb + Noun

Bài viết này tập trung vào semantics, không tập trung vào style.


3. Các thành phần ngữ nghĩa cơ bản

Tên trong code thường được cấu thành từ nhiều thành phần logic.

Thành phầnVai trò
Verbhành động
Nounobject/dữ liệu/domain
Adjectivetrạng thái/tính chất
Prefix logicbiểu diễn logic (is, has, can, ...)
Context wordbiểu diễn ngữ cảnh/thời điểm/trạng thái

4. Pattern đặt tên cho Variable


4.1 Variable thông thường

Pattern phổ biến​

Noun​

user
file
buffer
connection

Dùng cho object đơn giản hoặc domain object rõ ràng.


Adjective + Noun​

currentIndex
activeConnection
maxBufferSize
pendingRequest

Dùng khi object có thêm trạng thái hoặc tính chất.


Noun + Noun​

filePath
userName
errorMessage
windowTitle

Dùng để mô tả domain object cụ thể hơn.


Ý 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 variable phải đọc được như một câu logic tự nhiên.


Pattern chuẩn​

is + Adjective​

isOpen
isVisible
isEnabled
isConnected

Biểu diễn trạng thái.


has + Noun​

hasValue
hasChildren
hasPermission
hasFocus

Biểu diễn sự tồn tại hoặc ownership.


can + Verb​

canRead
canWrite
canExecute

Biểu diễn capability.


should + Verb​

shouldClose
shouldReload
shouldUpdate

Biểu diễn quyết định logic hoặc policy.


was + VerbPast​

wasLoaded
wasInitialized
wasProcessed

Biểu diễn trạng thái đã xảy ra trong quá khứ.


Vì sao pattern này quan trọng?​

Đoạn code:

if (isOpen)

đọc tự nhiên như tiếng Anh.

Trong khi:

if (open)

không mô tả rõ open là:

  • action?
  • state?
  • command?
  • function?

Bool naming tốt giúp giảm ambiguity rất mạnh.


4.3 Container Variable

Container nên biểu diễn “tập hợp”, không nên phản ánh implementation detail.


Pattern chuẩn​

Plural Noun​

users
files
tasks
connections
windows

Sai phổ biến​

userVector
taskList
fileArray

Vấn đề:

  • coupling với implementation
  • sau này đổi container sẽ gây tên sai ngữ nghĩa
  • làm lộ detail không cần thiết

Ví dụ:

std::vector<User> users;

sau này đổi sang:

std::unordered_map<ID, User>

thì tên userVector trở nên vô nghĩa.


4.4 Variable biểu diễn ownership

Rất quan trọng trong C++ hiện đại.

Tên nên phản ánh ownership semantics.


Pattern​

owned + Noun​

ownedBuffer
ownedWindow

Object sở hữu tài nguyên.


shared + Noun​

sharedConfig
sharedSession

Shared ownership.


weak + Noun​

weakParent
weakSession

Weak reference.


borrowed + Noun​

borrowedView
borrowedBuffer

Không sở hữu object.


Ý nghĩa​

PrefixSemantics
ownedunique ownership
sharedshared ownership
weakweak reference
borrowednon-owning reference/view

4.5 Variable biểu diễn trạng thái thời gian

Dùng khi object thay đổi theo timeline hoặc state machine.


Pattern​

current + Noun​

currentState
currentIndex

next + Noun​

nextFrame
nextNode

previous + Noun​

previousNode
previousState

pending + Noun​

pendingRequest
pendingTask

4.6 Constant / Config Variable

Dùng cho giới hạn, cấu hình, giá trị mặc định.


Pattern​

max + Noun​

maxBufferSize
maxConnections

min + Noun​

minValue
minCapacity

default + Noun​

defaultTimeout
defaultFontSize

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​

openFile()
closeConnection()
loadTexture()
parseConfig()

Ý nghĩa​

Thành phầnVai trò
Verbhành động
Nounobject bị tác động

5.2 Getter Function

Trong C++ hiện đại, getter thường mang semantics của property.


Pattern khuyến nghị​

Noun​

size()
name()
data()
path()

Adjective + Noun​

filePath()
bufferSize()
currentState()

Không nên​

getSize()
getName()
getData()

trừ khi:

  • codebase đang dùng convention Java/C#
  • framework yêu cầu pattern này

Lý do​

buffer.size()

đọc giống property access hơn:

buffer.getSize()

5.3 Setter Function

Pattern​

set + Noun​

setName()
setFilePath()
setBufferSize()

Setter biểu diễn mutation rõ ràng.


5.4 Bool Function

Bool function nên đọc như câu hỏi logic.


Pattern​

is + Adjective​

isOpen()
isEmpty()

has + Noun​

hasValue()
hasChildren()

can + Verb​

canRead()
canExecute()

should + Verb​

shouldReload()
shouldClose()

contains + Noun​

containsKey()
containsUser()

5.5 Factory Function

Factory function biểu diễn việc tạo object.


Pattern​

create + Noun​

createWindow()
createRenderer()

Tạo object hoàn chỉnh.


make + Noun​

makeRequest()
makeError()

Thường dùng cho utility/simple construction.


build + Noun​

buildPipeline()
buildCommandBuffer()

Tạo object theo nhiều bước hoặc builder-style.


generate + Noun​

generateToken()
generateUUID()

Sinh dữ liệu.


Khác biệt semantics​

VerbÝ nghĩa
createtạo object hoàn chỉnh
makeutility/simple construction
buildtạo nhiều bước
generatesinh dữ liệu

5.6 Conversion Function


Pattern​

to + Noun​

toString()
toJson()

Tạo representation mới.


as + Noun​

asView()
asSpan()

View/cast nhẹ, thường không ownership.


from + Noun​

fromBytes()
fromString()

Khởi tạo object từ nguồn khác.


5.7 Mutation Function

Function thay đổi state nội bộ.


Pattern​

Verb​

clear()
reset()
resize()

Verb + Noun​

appendData()
removeUser()
insertNode()

5.8 Event Handler Function

Rất phổ biến trong GUI, async system và event-driven architecture.


Pattern​

on + Event​

onButtonPressed()
onTabClosed()

Thường là callback hoặc slot.


handle + Event​

handleMouseClick()
handleConnectionClosed()

Thường là logic xử lý event.


Khác biệt semantics​

PrefixÝ nghĩa
oncallback/event entry point
handlexử lý logic của event

5.9 Async / Thread / Task Function


Pattern​

start + Noun​

startWorker()
startThread()

stop + Noun​

stopWorker()
stopThread()

waitFor + Noun​

waitForCompletion()
waitForShutdown()

5.10 Validation Function


Pattern​

validate + Noun​

validateConfig()
validateInput()

Kiểm tra hợp lệ logic.


check + Noun​

checkPermission()
checkBounds()

Kiểm tra tổng quát.


verify + Noun​

verifyChecksum()
verifySignature()

Xác minh tính đúng đắn hoặc integrity.


5.11 Search / Query Function


Pattern​

find + Noun​

findUser()
findWindow()

Tìm object cụ thể.


search + Noun​

searchFiles()
searchSymbols()

Tìm nhiều kết quả.


query + Noun​

queryDatabase()
queryUsers()

Truy vấn dữ liệu hoặc backend.


6. Đặt tên trong 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

handleSyntaxHighlightingFromAddTabRequested()

Vấn đề​

Tên đang encode quá nhiều thứ:

  • subsystem
  • event source
  • event state
  • action
  • workflow

vào một chuỗi tuyến tính duy nhất.

Điều này thường phản ánh:

  • abstraction chưa rõ
  • responsibility chưa tách
  • coupling quá mạnh

6.2 Hướng thiết kế tốt hơn

Tách:

  • event handling
  • business logic

Ví dụ​

void MainWindow::onAddTabRequested()
{
configureSyntaxHighlightingForTab();
}

Kết quả​

FunctionResponsibility
onAddTabRequested()UI event
configureSyntaxHighlightingForTab()business logic

Tên ngắn hơn nhưng semantics rõ hơn.


7. Các quy tắc ngữ nghĩa quan trọng


7.1 Tên phải phản ánh intent, không phản ánh implementation


Sai​

sortVector()

Tên đang nói về implementation detail.


Đúng​

sortUsers()

Tên phản ánh domain intent.


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 database

Tên gây hiểu lầm rằng operation nhẹ.


Đúng​

loadData()
fetchData()
parseData()

Tên phản ánh behavior thực sự.


7.3 Tránh meaningless words


Sai​

data
value
info
temp
object
manager
helper

Các từ này quá generic.

Chúng thường là dấu hiệu của:

  • abstraction mơ hồ
  • responsibility không rõ
  • thiết kế chưa hoàn chỉnh

7.4 Tránh dư thừa context


Sai​

class User {
private:
std::string m_userName;
};

Trong class User, prefix user là dư thừa.


Đúng​

class User {
private:
std::string m_name;
};

Context của class đã cung cấp ý nghĩa.


8. Tổng hợp các pattern quan trọng

PatternÝ nghĩa
Verb + Nounaction
Adjective + Nounstate/property
Noun + Noundomain object
is + Adjectivebool state
has + Nounexistence/ownership
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/default

9. Kết luận

Đặt tên trong C++ hiện đại không phải:

đặ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 nhanh
  • giảm ambiguity
  • giảm cognitive load
  • giảm nhu cầu đọc implementation

Mục tiêu cuối cùng:

code có khả năng tự mô tả hành vi và vai trò của chính nó.