naming-cheatsheet
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNaming 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:
| Principle | Description |
|---|---|
| Short | Not take long to type and remember |
| Intuitive | Read naturally, close to common speech |
| Descriptive | Reflect 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 > 10The A/HC/LC Pattern
A/HC/LC命名模式
The core pattern for naming functions:
prefix? + action (A) + high context (HC) + low context? (LC)| Name | Prefix | Action (A) | High Context (HC) | Low Context (LC) |
|---|---|---|---|---|
| | | ||
| | | | |
| | | | |
| | | |
Context order matters: means you update the component, while means component updates itself.
shouldUpdateComponentshouldComponentUpdate函数命名的核心模式:
前缀? + 动作(A) + 高语境(HC) + 低语境?(LC)| 名称 | 前缀 | 动作(A) | 高语境(HC) | 低语境(LC) |
|---|---|---|---|---|
| | | ||
| | | | |
| | | | |
| | | |
语境顺序至关重要:表示你来更新组件,而表示组件自行更新。
shouldUpdateComponentshouldComponentUpdateActions (Verbs)
动作动词
get
getget
getAccesses 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
setset
setSets 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
resetreset
resetSets 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
removedeleteremove
vs delete
removedelete| Action | Use Case | Opposite |
|---|---|---|
| Removes something from a collection | |
| Completely erases from existence | |
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: needs a destination, does not. Pair with , with .
addcreateremoveadddeletecreate| 动作 | 使用场景 | 对应反向操作 |
|---|---|---|
| 从集合中移除某元素 | |
| 彻底删除元素使其不复存在 | |
javascript
// remove - 从集合中移除(与add配对使用)
function removeFilter(filterName, filters) {
return filters.filter((name) => name !== filterName)
}
// delete - 永久删除(与create配对使用)
function deletePost(id) {
return database.find({ id }).delete()
}关键要点:需要指定目标位置,则不需要。与配对,与配对。
addcreateremoveadddeletecreatecompose
composecompose
composeCreates new data from existing data.
javascript
function composePageUrl(pageName, pageId) {
return pageName.toLowerCase() + '-' + pageId
}基于现有数据生成新数据。
javascript
function composePageUrl(pageName, pageId) {
return pageName.toLowerCase() + '-' + pageId
}handle
handlehandle
handleHandles 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
布尔类型前缀
| Prefix | Usage | Example |
|---|---|---|
| Describes characteristic or state | |
| Describes possession of value or state | |
| Positive conditional coupled with action | |
javascript
/* Bad */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0
/* Good */
const hasProducts = productsCount > 0| 前缀 | 用法 | 示例 |
|---|---|---|
| 描述特征或状态 | |
| 描述是否拥有某值或处于某状态 | |
| 与动作搭配的正向条件判断 | |
javascript
/* 不佳示例 */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0
/* 良好示例 */
const hasProducts = productsCount > 0Boundary Prefixes
边界前缀
| Prefix | Usage | Example |
|---|---|---|
| Minimum or maximum value | |
| Previous or next state | |
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 })
}| 前缀 | 用法 | 示例 |
|---|---|---|
| 最小值或最大值 | |
| 前一个或后一个状态 | |
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 (, , ) and stick to it.
camelCasePascalCasesnake_casejavascript
/* Bad - inconsistent */
const page_count = 5
const shouldUpdate = true
/* Good - consistent */
const pageCount = 5
const shouldUpdate = true选择一种命名风格(、、)并保持统一。
camelCasePascalCasesnake_casejavascript
/* 不佳示例 - 风格不一致 */
const page_count = 5
const shouldUpdate = true
/* 良好示例 - 风格统一 */
const pageCount = 5
const shouldUpdate = true3. 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
快速参考
| Pattern | Example |
|---|---|
| Get single item | |
| Get collection | |
| Get nested | |
| Set value | |
| Reset to initial | |
| Add to collection | |
| Remove from collection | |
| Create new entity | |
| Delete permanently | |
| Compose/build | |
| Handle event | |
| Boolean state | |
| Boundaries | |
| State transitions | |
Source: kettanaito/naming-cheatsheet
| 模式 | 示例 |
|---|---|
| 获取单个元素 | |
| 获取集合 | |
| 获取嵌套元素 | |
| 设置值 | |
| 重置为初始状态 | |
| 添加至集合 | |
| 从集合中移除元素 | |
| 创建新实体 | |
| 永久删除 | |
| 组合/构建 | |
| 处理事件 | |
| 布尔状态 | |
| 边界值 | |
| 状态转换 | |