变量命名 函数命名 方法 Naming cheatsheet
- English language
- Naming convention
- S-I-D
- Avoid contractions
- Reflect the expected result
- Naming functions
- Singular and Plurals
Naming things is hard. This sheet attempts to make it easier.
Although these suggestions can be applied to any programming language, I will use JavaScript to illustrate them in practice.
English language
- Use English language when naming your variables and functions.
Naming convention
- Pick one naming convention and follow it. It may be camelCase, PascalCase, snake_case, or anything else, as long as it remains consistent. Many programming languages have their own traditions regarding naming conventions; check the documentation for your language or study some popular repositories on Github!
S-I-D
- Short. A name must not take long to type and, therefore, remember;
- Intuitive. A name must read naturally, as close to the common speech as possible;
- Descriptive. A name must reflect what it does/possesses in the most efficient way.
Avoid contractions
- Do not use contractions. They contribute to nothing but decreased readability of the code. Finding a short, descriptive name may be hard, but contraction is not an excuse for not doing so.
class MenuItem {
/* Method name duplicates the context (which is "MenuItem") */
handleMenuItemClick = (event) => { ... }
/* Reads nicely as `MenuItem.handleClick()` */
handleClick = (event) => { ... }
}
Reflect the expected result
- A name should reflect the expected result.
/* Bad */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />
/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />
Naming functions
- A/HC/LC pattern
- There is a useful pattern to follow when naming functions
prefix? + action (A) + high context (HC) + low context? (LC)
- Take a look at how this pattern may be applied in the table below.
- Actions
- get,set,reset,fetch,remove,delete,compose,handle
- Context
- A domain that a function operates on.
- Prefixes
- Prefix enhances the meaning of a variable. It is rarely used in function names.
- is,has,should,min/max,prev/next
Singular and Plurals
- Like a prefix, variable names can be made singular or plural depending on whether they hold a single value or multiple values.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)