Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork927
Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.
License
kettanaito/naming-cheatsheet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- Naming convention
- S-I-D
- Avoid contractions
- Avoid context duplication
- Reflect 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.
Pickone naming convention and follow it. It may becamelCase, orsnake_case, or anyhow else, it does not matter. What matters is for it to remain consistent.
/* Bad */constpages_count=5constshouldUpdate=true/* Good */constpagesCount=5constshouldUpdate=true/* Good as well */constpages_count=5constshould_update=true
A name must beshort,intuitive anddescriptive:
- 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 */consta=5// "a" could mean anythingconstisPaginatable=postsCount>10// "Paginatable" sounds extremely unnaturalconstshouldPaginatize=postsCount>10// Made up verbs are so much fun!/* Good */constpostsCount=5consthasPagination=postsCount>10constshouldDisplayPagination=postsCount>10// alternatively
Donot 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 */constonItmClk=()=>{}/* Good */constonItemClick=()=>{}
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.
classMenuItem{/* Method name duplicates the context (which is "MenuItem") */handleMenuItemClick=(event)=>{ ...}/* Reads nicely as `MenuItem.handleClick()` */handleClick=(event)=>{ ...}}
A name should reflect the expected result.
/* Bad */constisEnabled=itemsCount>3return<Buttondisabled={!isEnabled}/>/* Good */constisDisabled=itemsCount<=3return<Buttondisabled={isDisabled}/>
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.
| Name | Prefix | Action (A) | High context (HC) | Low context (LC) |
|---|---|---|---|---|
getPost | get | Post | ||
getPostData | get | Post | Data | |
handleClickOutside | handle | Click | Outside | |
shouldDisplayMessage | should | Display | Message |
Note: The order of context affects the meaning of a variable. For example,
shouldUpdateComponentmeansyou are about to update a component, whileshouldComponentUpdatetells you thatcomponent will update on itself, and you are but controlling when it should be updated.In other words,high context emphasizes the meaning of a variable.
The verb part of your function name. The most important part responsible for describing what the functiondoes.
Accesses data immediately (i.e. shorthand getter of internal data).
functiongetFruitsCount(){returnthis.fruits.length}
See alsocompose.
Sets a variable in a declarative way, with valueA to valueB.
constfruits=0functionsetFruits(nextFruits){fruits=nextFruits}setFruits(5)console.log(fruits)// 5
Sets a variable back to its initial value or state.
constinitialFruits=5constfruits=initialFruitssetFruits(10)console.log(fruits)// 10functionresetFruits(){fruits=initialFruits}resetFruits()console.log(fruits)// 5
Request for some data, which takes some indeterminate time (i.e. async request).
functionfetchPosts(postCount){returnfetch('https://api.dev/posts',{...})}
Removes somethingfrom somewhere.
For example, if you have a collection of selected filters on a search page, removing one of them from the collection isremoveFilter,notdeleteFilter (and this is how you would naturally say it in English as well):
functionremoveFilter(filterName,filters){returnfilters.filter((name)=>name!==filterName)}constselectedFilters=['price','availability','size']removeFilter('price',selectedFilters)
See alsodelete.
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 adeletePost action,notremovePost.
functiondeletePost(id){returndatabase.find({ id}).delete()}
See alsoremove.
Creates new data from the existing one. Mostly applicable to strings, objects, or functions.
functioncomposePageUrl(pageName,pageId){return`${pageName.toLowerCase()}-${pageId}`}
See alsoget.
Handles an action. Often used when naming a callback method.
functionhandleLinkClick(){console.log('Clicked a link!')}link.addEventListener('click',handleLinkClick)
A domain that a function operates on.
A function is often an action onsomething. It is important to state what is its operable domain, or at least an expected data type.
/* A pure function operating with primitives */functionfilter(predicate,list){returnlist.filter(predicate)}/* Function operating exactly on posts */functiongetRecentPosts(posts){returnfilter(posts,(post)=>post.date===Date.now())}
Some language-specific assumptions may allow omitting the context. For example, in JavaScript, it's common that
filteroperates on Array. Adding explicitfilterArraywould be unnecessary.
--
Prefix enhances the meaning of a variable. It is rarely used in function names.
Describes a characteristic or state of the current context (usuallyboolean).
constcolor='blue'constisBlue=color==='blue'// characteristicconstisPresent=true// stateif(isBlue&&isPresent){console.log('Blue is present!')}
Describes whether the current context possesses a certain value or state (usuallyboolean).
/* Bad */constisProductsExist=productsCount>0constareProductsPresent=productsCount>0/* Good */consthasProducts=productsCount>0
Reflects a positive conditional statement (usuallyboolean) coupled with a certain action.
functionshouldUpdateUrl(url,expectedUrl){returnurl!==expectedUrl}
Represents a minimum or maximum value. Used when describing boundaries or limits.
/** * Renders a random amount of posts within * the given min/max boundaries. */functionrenderPosts(posts,minPosts,maxPosts){returnposts.slice(0,randomBetween(minPosts,maxPosts))}
Indicate the previous or the next state of a variable in the current context. Used when describing state transitions.
functionfetchPosts(){constprevPosts=this.state.postsconstfetchedPosts=fetch('...')constnextPosts=concat(prevPosts,fetchedPosts)this.setState({posts:nextPosts})}
Like a prefix, variable names can be made singular or plural depending on whether they hold a single value or multiple values.
/* Bad */constfriends='Bob'constfriend=['Bob','Tony','Tanya']/* Good */constfriend='Bob'constfriends=['Bob','Tony','Tanya']
About
Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
