kettanaito/naming-cheatsheet là dự án mã nguồn mở trên GitHub với 14.2k sao. Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
VÌ SAO CHƯA CÓ REVIEW
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
Like it or not, English is the dominant language in programming: the syntax of all programming languages is written in English, as well as countless documentations and educational materials. By writing your code in English you dramatically increase its cohesiveness.
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!
/* Bad */
const page_count = 5
const shouldUpdate = true
/* Good */
const pageCount = 5
const shouldUpdate = true
/* Good as well */
const page_count = 5
const should_update = true
S-I-D
A name must be short, intuitive and descriptive:
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.
/* Bad */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural
const shouldPaginatize = a > 10 // Made up verbs are so much fun!
/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively
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.
/* Bad */
const onItmClk = () => {}
/* Good */
const onItemClick = () => {}
Avoid context duplication
A name should not duplicate the context in which it is defined. Always remove the context from a name if that doesn't decrease its readability.
class MenuItem {
/* Method name duplicates the context (which is "MenuItem") */
handleMenuItemClick = (event) => { ... }
/* Reads nicely as `MenuItem.handleClick()` */
handleClick = (event) => { ... }
}
Take a look at how this pattern may be applied in the table below.
Name
Prefix
Action (A)
High context (HC)
Low context (LC)
getUser
get
User
getUserMessages
get
User
Messages
handleClickOutside
handle
Click
Outside
shouldDisplayMessage
should
Display
Message
Note: The order of context affects the meaning of a variable. For example, shouldUpdateComponent means you are about to update a component, while shouldComponentUpdate tells you that component will update itself, and you are only controlling when it should update.
In other words, high context emphasizes the meaning of a variable.
Actions
The verb part of your function name. The most important part responsible for describing what the function does.
get
Accesses data immediately (i.e. shorthand getter of internal data).
function getFruitCount() {
return this.fruits.length
}
See also compose.
You can use get when performing asynchronous operations as well:
async function getUser(id) {
const user = await fetch(`/api/user/${id}`)
return user
}
set
Sets a variable in a declarative way, with value A to value B.
let fruits = 0
function setFruits(nextFruits) {
fruits = nextFruits
}
setFruits(5)
console.log(fruits) // 5
reset
Sets a variable back to its initial value or state.
For example, if you have a collection of selected filters on a search page, removing one of them from the collection is removeFilter, notdeleteFilter (and this is how you would naturally say it in English as well):
function removeFilter(filterName, filters) {
return filters.filter((name) => name !== filterName)
}
const selectedFilters = ['price', 'availability', 'size']
removeFilter('price', selectedFilters)
See also delete.
delete
Completely erases something from the realms of existence.
Imagine you are a content editor, and there is that notorious post you wish to get rid of. Once you clicked a shiny "Delete post" button, the CMS performed a deletePost action, notremovePost.
function deletePost(id) {
return database.find({ id }).delete()
}
See also remove.
remove or delete?
When the difference between remove and delete is not so obvious to you, I'd suggest looking at their opposite actions - add and create.
The key difference between add and create is that add needs a destination while createrequires no destination. You add an item to somewhere, but you don't "create it to somewhere".
Simply pair remove with add and delete with create.
Explained in detail here.
compose
Creates new data from the existing one. Mostly applicable to strings, objects, or functions.
Handles an action. Often used when naming a callback method.
function handleLinkClick() {
console.log('Clicked a link!')
}
link.addEventListener('click', handleLinkClick)
Context
A domain that a function operates on.
A function is often an action on something. It is important to state what its operable domain is, or at least an expected data type.
/* A pure function operating with primitives */
function filter(list, predicate) {
return list.filter(predicate)
}
/* Function operating exactly on posts */
function getRecentPosts(posts) {
return filter(posts, (post) => post.date === Date.now())
}
Some language-specific assumptions may allow omitting the context. For example, in JavaScript, it's common that filter operates on Array. Adding explicit filterArray would be unnecessary.
Prefixes
Prefix enhances the meaning of a variable. It is rarely used in function names.
is
Describes a characteristic or state of the current context (usually boolean).
const color = 'blue'
const isBlue = color === 'blue' // characteristic
const isPresent = true // state
if (isBlue && isPresent) {
console.log('Blue is present!')
}
has
Describes whether the current context possesses a certain value or state (usually boolean).
Reflects a positive conditional statement (usually boolean) coupled with a certain action.
function shouldUpdateUrl(url, expectedUrl) {
return url !== expectedUrl
}
min/max
Represents a minimum or maximum value. Used when describing boundaries or limits.
/**
* Renders a random amount of posts within
* the given min/max boundaries.
*/
function renderPosts(posts, minPosts, maxPosts) {
return posts.slice(0, randomBetween(minPosts, maxPosts))
}
prev/next
Indicate the previous or the next state of a variable in the current context. Used when describing state transitions.
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/kettanaito/naming-cheatsheet là nguồn chính thức.
kettanaito/naming-cheatsheet có phải mã nguồn mở không?
Có — kettanaito/naming-cheatsheet phát hành theo license MIT, nghĩa là mã nguồn mở để đọc, fork và (tùy license) tái sử dụng. Mã: github.com/kettanaito/naming-cheatsheet.
kettanaito/naming-cheatsheet là gì?
kettanaito/naming-cheatsheet (kettanaito/naming-cheatsheet) là dự án đa ngôn ngữ trên GitHub. Theo mô tả gốc: Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.
Đọc đầy đủ README ở tab phía trên.
Muốn nghe thêm một ý kiến về naming-cheatsheet?
Hỏi một AI đọc được trang này — một cú bấm là có ngay nhận định về naming-cheatsheet.