Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Comprehensive language-agnostic guidelines on variables naming.

License

NotificationsYou must be signed in to change notification settings

illicitonion/naming-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 

Repository files navigation

Naming cheatsheet

Naming cheatsheet

Naming things is hard. Let's make it easier.

This document contains systematized concepts and patterns often used when naming variables.

Summary

Guidelines

  • Pickone naming convention and follow it. Whether it islikeThis, 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}/>);

HC/LC Pattern

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.

NamePrefixActionHigh contextLow context
getPostgetPost
getPostDatagetPostData
handleClickOutsidehandleClickOutside
shouldDisplayMessageshouldDisplayMessage

Note: The order of the contexts affects the core meaning of a method. For example,shouldUpdateComponent meansyou are about to update a component, whileshouldComponentUpdate tells 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.


Actions

Chosing a proper action name may grant explicit descriptiveness to your methods. This is a good place to start when naming your methods.

get

Accesses data immediately (i.e. shorthand getter of internal data).

functiongetFruitsCount(){returnthis.fruits.length;}

set

Declaratively sets a variable with valueA to valueB.

constfruits=0;functionsetFruits(nextFruits){fruits=nextFruits;}setFruits(5);console.log(fruits)// 5

reset

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

fetch

Requests for a data, which takes time (i.e. async request).

functionfetchPosts(postCount){returnfetch('https://api.dev/posts',{ ...});}

remove

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;}

delete

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();}

compose

Creates a new data from the existing one. Mostly applicable to strings or objects.

functioncomposePageUrl(pageName,pageId){return`${pageName.toLowerCase()}-${pageId}`;}

handle

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

Prefixes act as enhancers, indicating additional meaning behind variables.

is

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!');}

has

Describes whether the current context possesses a certain value or state (returnsBoolean).

/* Bad */constisProductsExist=(productsCount>0);constareProductsPresent=(productsCount>0);/* Good */consthasProducts=(productsCount>0);

should

Reflects a positive conditional statement (returnsBoolean) tightly coupled with a certain action.

constcurrentUrl='https://dev.com';functionshouldUpdateUrl(url){return(url!==currentUrl);}

min/max

Represent minimum or maximum value. Useful for describing boundaries or allowed limits.

functionPostsList(){this.minPosts=3;this.maxPosts=10;}

prev/next

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp