- Notifications
You must be signed in to change notification settings - Fork0
Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.
License
Nastya318/naming-cheatsheet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- English language
- Naming convention
- S-I-D
- Avoid contractions
- Avoid context duplication
- 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.
Use English language when naming your variables and functions.
/* Bad */constprimerNombre='Gustavo'constamigos=['Kate','John']/* Good */constfirstName='Gustavo'constfriends=['Kate','John']
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.
Pickone naming convention and follow it. It may becamelCase,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 */constpage_count=5constshouldUpdate=true/* Good */constpageCount=5constshouldUpdate=true/* Good as well */constpage_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=a>10// "Paginatable" sounds extremely unnaturalconstshouldPaginatize=a>10// Made up verbs are so much fun!/* Good */constpostCount=5consthasPagination=postCount>10constshouldPaginate=postCount>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=itemCount>3return<Buttondisabled={!isEnabled}/>/* Good */constisDisabled=itemCount<=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) |
|---|---|---|---|---|
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,
shouldUpdateComponentmeansyou are about to update a component, whileshouldComponentUpdatetells you thatcomponent will update itself, and you are only controllingwhen it should update.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).
functiongetFruitCount(){returnthis.fruits.length}
See alsocompose.
You can useget when performing asynchronous operations as well:
asyncfunctiongetUser(id){constuser=awaitfetch(`/api/user/${id}`)returnuser}
Sets a variable in a declarative way, with valueA to valueB.
letfruits=0functionsetFruits(nextFruits){fruits=nextFruits}setFruits(5)console.log(fruits)// 5
Sets a variable back to its initial value or state.
constinitialFruits=5letfruits=initialFruitssetFruits(10)console.log(fruits)// 10functionresetFruits(){fruits=initialFruits}resetFruits()console.log(fruits)// 5
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.
removeordelete?When the difference between
removeanddeleteis not so obvious to you, I'd suggest looking at their opposite actions -addandcreate.The key difference betweenaddandcreateis thataddneeds a destination whilecreaterequires no destination. Youaddan itemto somewhere, but you don't "createitto somewhere".Simply pairremovewithaddanddeletewithcreate.Explained in detailhere.
Creates new data from the existing one. Mostly applicable to strings, objects, or functions.
functioncomposePageUrl(pageName,pageId){returnpageName.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 its operable domain is, or at least an expected data type.
/* A pure function operating with primitives */functionfilter(list,predicate){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.
asyncfunctiongetPosts(){constprevPosts=this.state.postsconstlatestPosts=awaitfetch('...')constnextPosts=concat(prevPosts,latestPosts)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.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
