naming-cheatsheet

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Naming Cheatsheet

命名速查表

Comprehensive guidelines for naming variables and functions in any programming language, based on the A/HC/LC pattern.
基于A/HC/LC模式的多编程语言变量与函数命名综合指南。

When to Use

适用场景

  • Naming new variables, functions, or classes
  • Reviewing code for naming consistency
  • Refactoring poorly named identifiers
  • Teaching or establishing team naming conventions
  • 为新变量、函数或类命名
  • 审查代码的命名一致性
  • 重构命名不佳的标识符
  • 教学或制定团队命名规范

Core Principles (S-I-D)

核心原则(S-I-D)

Names must be:
PrincipleDescription
ShortNot take long to type and remember
IntuitiveRead naturally, close to common speech
DescriptiveReflect what it does/possesses in the most efficient way
javascript
/* Bad */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // sounds unnatural
const shouldPaginatize = a > 10 // made-up verb

/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10
命名必须满足:
原则描述
简短便于输入和记忆
直观符合日常表达习惯,易于理解
表意明确以最简洁的方式体现其功能或所代表的内容
javascript
/* 不佳示例 */
const a = 5 // "a"可以指代任何内容
const isPaginatable = a > 10 // 表述生硬
const shouldPaginatize = a > 10 // 生造动词

/* 良好示例 */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10

The A/HC/LC Pattern

A/HC/LC命名模式

The core pattern for naming functions:
prefix? + action (A) + high context (HC) + low context? (LC)
NamePrefixAction (A)High Context (HC)Low Context (LC)
getUser
get
User
getUserMessages
get
User
Messages
handleClickOutside
handle
Click
Outside
shouldDisplayMessage
should
Display
Message
Context order matters:
shouldUpdateComponent
means you update the component, while
shouldComponentUpdate
means component updates itself.
函数命名的核心模式:
前缀? + 动作(A) + 高语境(HC) + 低语境?(LC)
名称前缀动作(A)高语境(HC)低语境(LC)
getUser
get
User
getUserMessages
get
User
Messages
handleClickOutside
handle
Click
Outside
shouldDisplayMessage
should
Display
Message
语境顺序至关重要
shouldUpdateComponent
表示来更新组件,而
shouldComponentUpdate
表示组件自行更新。

Actions (Verbs)

动作动词

get

get

Accesses data immediately (shorthand getter). Also used for async operations.
javascript
function getFruitCount() {
  return this.fruits.length
}

async function getUser(id) {
  const user = await fetch(`/api/user/${id}`)
  return user
}
直接获取数据(简写的获取器),也可用于异步操作。
javascript
function getFruitCount() {
  return this.fruits.length
}

async function getUser(id) {
  const user = await fetch(`/api/user/${id}`)
  return user
}

set

set

Sets a variable declaratively, from value A to value B.
javascript
let fruits = 0

function setFruits(nextFruits) {
  fruits = nextFruits
}
声明式地将变量从值A设置为值B。
javascript
let fruits = 0

function setFruits(nextFruits) {
  fruits = nextFruits
}

reset

reset

Sets a variable back to its initial value or state.
javascript
const initialFruits = 5
let fruits = initialFruits

function resetFruits() {
  fruits = initialFruits
}
将变量重置为初始值或初始状态。
javascript
const initialFruits = 5
let fruits = initialFruits

function resetFruits() {
  fruits = initialFruits
}

remove
vs
delete

remove
vs
delete

ActionUse CaseOpposite
remove
Removes something from a collection
add
delete
Completely erases from existence
create
javascript
// remove - from a collection (paired with add)
function removeFilter(filterName, filters) {
  return filters.filter((name) => name !== filterName)
}

// delete - permanent erasure (paired with create)
function deletePost(id) {
  return database.find({ id }).delete()
}
Key insight:
add
needs a destination,
create
does not. Pair
remove
with
add
,
delete
with
create
.
动作使用场景对应反向操作
remove
从集合中移除某元素
add
delete
彻底删除元素使其不复存在
create
javascript
// remove - 从集合中移除(与add配对使用)
function removeFilter(filterName, filters) {
  return filters.filter((name) => name !== filterName)
}

// delete - 永久删除(与create配对使用)
function deletePost(id) {
  return database.find({ id }).delete()
}
关键要点
add
需要指定目标位置,
create
则不需要。
remove
add
配对,
delete
create
配对。

compose

compose

Creates new data from existing data.
javascript
function composePageUrl(pageName, pageId) {
  return pageName.toLowerCase() + '-' + pageId
}
基于现有数据生成新数据。
javascript
function composePageUrl(pageName, pageId) {
  return pageName.toLowerCase() + '-' + pageId
}

handle

handle

Handles an action, often used for callback methods.
javascript
function handleLinkClick() {
  console.log('Clicked a link!')
}

link.addEventListener('click', handleLinkClick)
处理某个动作,常用于回调方法。
javascript
function handleLinkClick() {
  console.log('点击了链接!')
}

link.addEventListener('click', handleLinkClick)

Prefixes

前缀

Boolean Prefixes

布尔类型前缀

PrefixUsageExample
is
Describes characteristic or state
isBlue
,
isPresent
,
isEnabled
has
Describes possession of value or state
hasProducts
,
hasPermission
should
Positive conditional coupled with action
shouldUpdateUrl
,
shouldDisplayMessage
javascript
/* Bad */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0

/* Good */
const hasProducts = productsCount > 0
前缀用法示例
is
描述特征或状态
isBlue
,
isPresent
,
isEnabled
has
描述是否拥有某值或处于某状态
hasProducts
,
hasPermission
should
与动作搭配的正向条件判断
shouldUpdateUrl
,
shouldDisplayMessage
javascript
/* 不佳示例 */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0

/* 良好示例 */
const hasProducts = productsCount > 0

Boundary Prefixes

边界前缀

PrefixUsageExample
min
/
max
Minimum or maximum value
minPosts
,
maxRetries
prev
/
next
Previous or next state
prevPosts
,
nextPosts
javascript
function renderPosts(posts, minPosts, maxPosts) {
  return posts.slice(0, randomBetween(minPosts, maxPosts))
}

async function getPosts() {
  const prevPosts = this.state.posts
  const latestPosts = await fetch('...')
  const nextPosts = concat(prevPosts, latestPosts)
  this.setState({ posts: nextPosts })
}
前缀用法示例
min
/
max
最小值或最大值
minPosts
,
maxRetries
prev
/
next
前一个或后一个状态
prevPosts
,
nextPosts
javascript
function renderPosts(posts, minPosts, maxPosts) {
  return posts.slice(0, randomBetween(minPosts, maxPosts))
}

async function getPosts() {
  const prevPosts = this.state.posts
  const latestPosts = await fetch('...')
  const nextPosts = concat(prevPosts, latestPosts)
  this.setState({ posts: nextPosts })
}

Rules to Follow

需遵循的规则

1. Use English Language

1. 使用英文命名

javascript
/* Bad */
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']

/* Good */
const firstName = 'Gustavo'
const friends = ['Kate', 'John']
javascript
/* 不佳示例 */
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']

/* 良好示例 */
const firstName = 'Gustavo'
const friends = ['Kate', 'John']

2. Be Consistent with Naming Convention

2. 保持命名风格一致

Pick one convention (
camelCase
,
PascalCase
,
snake_case
) and stick to it.
javascript
/* Bad - inconsistent */
const page_count = 5
const shouldUpdate = true

/* Good - consistent */
const pageCount = 5
const shouldUpdate = true
选择一种命名风格(
camelCase
PascalCase
snake_case
)并保持统一。
javascript
/* 不佳示例 - 风格不一致 */
const page_count = 5
const shouldUpdate = true

/* 良好示例 - 风格统一 */
const pageCount = 5
const shouldUpdate = true

3. Avoid Contractions

3. 避免缩写

javascript
/* Bad */
const onItmClk = () => {}

/* Good */
const onItemClick = () => {}
javascript
/* 不佳示例 */
const onItmClk = () => {}

/* 良好示例 */
const onItemClick = () => {}

4. Avoid Context Duplication

4. 避免语境重复

javascript
class MenuItem {
  /* Bad - duplicates context */
  handleMenuItemClick = (event) => { ... }

  /* Good - reads as MenuItem.handleClick() */
  handleClick = (event) => { ... }
}
javascript
class MenuItem {
  /* 不佳示例 - 重复语境 */
  handleMenuItemClick = (event) => { ... }

  /* 良好示例 - 可理解为MenuItem.handleClick() */
  handleClick = (event) => { ... }
}

5. Reflect Expected Result

5. 命名需反映预期结果

javascript
/* Bad */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />

/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />
javascript
/* 不佳示例 */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />

/* 良好示例 */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />

6. Use Singular/Plural Correctly

6. 正确使用单复数

javascript
/* Bad */
const friends = 'Bob'
const friend = ['Bob', 'Tony', 'Tanya']

/* Good */
const friend = 'Bob'
const friends = ['Bob', 'Tony', 'Tanya']
javascript
/* 不佳示例 */
const friends = 'Bob'
const friend = ['Bob', 'Tony', 'Tanya']

/* 良好示例 */
const friend = 'Bob'
const friends = ['Bob', 'Tony', 'Tanya']

Quick Reference

快速参考

PatternExample
Get single item
getUser
,
getPost
Get collection
getUsers
,
getPosts
Get nested
getUserMessages
Set value
setUser
,
setTheme
Reset to initial
resetForm
,
resetFilters
Add to collection
addItem
,
addFilter
Remove from collection
removeItem
,
removeFilter
Create new entity
createUser
,
createPost
Delete permanently
deleteUser
,
deletePost
Compose/build
composeUrl
,
buildQuery
Handle event
handleClick
,
handleSubmit
Boolean state
isActive
,
hasItems
,
shouldRender
Boundaries
minCount
,
maxRetries
State transitions
prevState
,
nextState

模式示例
获取单个元素
getUser
,
getPost
获取集合
getUsers
,
getPosts
获取嵌套元素
getUserMessages
设置值
setUser
,
setTheme
重置为初始状态
resetForm
,
resetFilters
添加至集合
addItem
,
addFilter
从集合中移除元素
removeItem
,
removeFilter
创建新实体
createUser
,
createPost
永久删除
deleteUser
,
deletePost
组合/构建
composeUrl
,
buildQuery
处理事件
handleClick
,
handleSubmit
布尔状态
isActive
,
hasItems
,
shouldRender
边界值
minCount
,
maxRetries
状态转换
prevState
,
nextState