- Notifications
You must be signed in to change notification settings - Fork0
Comprehensive language-agnostic guidelines on variables naming.
License
illicitonion/naming-cheatsheet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Naming things is hard. Let's make it easier.
This document contains systematized concepts and patterns often used when naming variables.
- Pickone naming convention and follow it. Whether it is
likeThis, orlike_this, or anyhow else, it does not matter. What matters is consistency in your code.
/* Bad */constpages_count=5;constshouldUpdate=true;/* Good */constpagesCount=5;constshouldUpdate=true;/* Good as well */constpages_count=5;constshould_update=true;
- Name, whether of a variable, method, or something else, should beshort,descriptive andintuitive:
- Short. Variable should not take long to type and, therefore, to remember,
- Descriptive. Name of the variable should reflect what it does/possesses in the most efficient way,
- Intuitive. Name of the variable should read naturally, as close to the common speach as possible
/* Bad */consta=5;// "a" could mean anythingconstisPaginatable=(postsCount>10);// "Paginatable" sounds extremely unnaturalconstshouldPaginatize=(postsCount>10);// Made up verbs are so much fun!/* Good */constpostsCount=5;constshouldDisplayPagination=(postsCount>10);
- Donot use contractions. The latter contribute to nothing but decreased code readability. Finding a short, descriptive name may be hard, but don't think contractions help you in any way.
/* Bad */constonItmClck=()=>{};/* Good */constonItemClick=()=>{};
- Name should not duplicate the context when the latter is known, and when removing the context does not decrease the name's readability:
classMenuItem{/* Method name duplicates the context it is in (which is "MenuItem") */handleMenuItemClick=(event)=>{ ...}/* This way it reads as MenuItem.handleClick() */handleClick=(event)=>{ ...}}
- Name should reflect the expected result:
/* Bad */constisEnabled=(itemsCount>3);return(<Buttondisabled={!isEnabled}/>);/* Good */constisDisabled=(itemsCount<=3);return(<Buttondisabled={isDisabled}/>);
There is a useful pattern you may follow when naming your methods:
prefix? + action (A) + high context (HC) + low context? (LC)To illustrate, take a look at how this pattern may be applied in the table below.
| Name | Prefix | Action | High context | Low context |
|---|---|---|---|---|
getPost | get | Post | ||
getPostData | get | Post | Data | |
handleClickOutside | handle | Click | Outside | |
shouldDisplayMessage | should | Display | Message |
Note: The order of the contexts affects the core meaning of a method. For example,
shouldUpdateComponentmeansyou are about to update a component, whileshouldComponentUpdatetells you thatcomponent will update on itself, and you are but controlling whether it should do that right now.In other words,high context emphasizes the meaning of the variable.
Chosing a proper action name may grant explicit descriptiveness to your methods. This is a good place to start when naming your methods.
Accesses data immediately (i.e. shorthand getter of internal data).
functiongetFruitsCount(){returnthis.fruits.length;}
Declaratively sets a variable with valueA to valueB.
constfruits=0;functionsetFruits(nextFruits){fruits=nextFruits;}setFruits(5);console.log(fruits)// 5
Sets a variable back to its initial value or state.
constinitialFruits=5;constfruits=initialFruits;setFruits(10);console.log(fruits);// 10functionresetFruits(){fruits=initialFruits;}resetFruits();console.log(fruits);// 5
Requests for a data, which takes 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):
constselectedFilters=['price','availability','size'];functionremoveFilter(filterName){constfilterIndex=selectedFilters.indexOf(filterName);if(filterIndex!==-1){selectedFilters.splice(filterIndex,1);}returnselectedFilters;}
Completely erazes something from the realms of existance.
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();}
Creates a new data from the existing one. Mostly applicable to strings or objects.
functioncomposePageUrl(pageName,pageId){return`${pageName.toLowerCase()}-${pageId}`;}
Handles a dedicated action. Often used in naming the callback methods.
functionhandleLinkClick(event){event.preventDefault();console.log('Clicked a link!');}link.addEventListener('click',handleLinkClick);
Prefixes act as enhancers, indicating additional meaning behind variables.
Describes certain characteristic or state of the current context (returnsBoolean).
constcolor='blue';constisBlue=(color==='blue');// characteristicconstisPresent=true;// stateif(isBlue&&isPresent){console.log('The color is blue and it is present!');}
Describes whether the current context possesses a certain value or state (returnsBoolean).
/* Bad */constisProductsExist=(productsCount>0);constareProductsPresent=(productsCount>0);/* Good */consthasProducts=(productsCount>0);
Reflects a positive conditional statement (returnsBoolean) tightly coupled with a certain action.
constcurrentUrl='https://dev.com';functionshouldUpdateUrl(url){return(url!==currentUrl);}
Represent minimum or maximum value. Useful for describing boundaries or allowed limits.
functionPostsList(){this.minPosts=3;this.maxPosts=10;}
Indicate the previous and the next state of a variable in the current context. Useful for describing state transitions.
functionfetchPosts(){constprevPosts=this.state.posts;constfetchedPosts=fetch('...');constnextPosts=prevPosts.merge(fetchedPosts);returnthis.setState({posts:nextPosts});}
About
Comprehensive language-agnostic guidelines on variables naming.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
