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. Home of the A/HC/LC pattern.

License

NotificationsYou must be signed in to change notification settings

kettanaito/naming-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

77 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Naming cheatsheet

Naming cheatsheet


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.

English language

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.

Naming convention

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

S-I-D

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

Avoid contractions

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=()=>{}

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.

classMenuItem{/* Method name duplicates the context (which is "MenuItem") */handleMenuItemClick=(event)=>{ ...}/* Reads nicely as `MenuItem.handleClick()` */handleClick=(event)=>{ ...}}

Reflect the expected result

A name should reflect the expected result.

/* Bad */constisEnabled=itemCount>3return<Buttondisabled={!isEnabled}/>/* Good */constisDisabled=itemCount<=3return<Buttondisabled={isDisabled}/>

Naming functions

A/HC/LC Pattern

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.

NamePrefixAction (A)High context (HC)Low context (LC)
getUsergetUser
getUserMessagesgetUserMessages
handleClickOutsidehandleClickOutside
shouldDisplayMessageshouldDisplayMessage

Note: The order of context affects the meaning of a variable. For example,shouldUpdateComponent meansyou are about to update a component, whileshouldComponentUpdate tells you thatcomponent will update itself, and you are only controllingwhen 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 functiondoes.

get

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}

set

Sets a variable in a declarative way, with valueA to valueB.

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

reset

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

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):

functionremoveFilter(filterName,filters){returnfilters.filter((name)=>name!==filterName)}constselectedFilters=['price','availability','size']removeFilter('price',selectedFilters)

See alsodelete.

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 adeletePost action,notremovePost.

functiondeletePost(id){returndatabase.find({ id}).delete()}

See alsoremove.

remove ordelete?

When the difference betweenremove anddelete is not so obvious to you, I'd suggest looking at their opposite actions -add andcreate.The key difference betweenadd andcreate is thatadd needs a destination whilecreaterequires no destination. Youadd an itemto somewhere, but you don't "create itto somewhere".Simply pairremove withadd anddelete withcreate.

Explained in detailhere.

compose

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

functioncomposePageUrl(pageName,pageId){returnpageName.toLowerCase()+'-'+pageId}

See alsoget.

handle

Handles an action. Often used when naming a callback method.

functionhandleLinkClick(){console.log('Clicked a link!')}link.addEventListener('click',handleLinkClick)

Context

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 thatfilter operates on Array. Adding explicitfilterArray 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 (usuallyboolean).

constcolor='blue'constisBlue=color==='blue'// characteristicconstisPresent=true// stateif(isBlue&&isPresent){console.log('Blue is present!')}

has

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

/* Bad */constisProductsExist=productsCount>0constareProductsPresent=productsCount>0/* Good */consthasProducts=productsCount>0

should

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

functionshouldUpdateUrl(url,expectedUrl){returnurl!==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. */functionrenderPosts(posts,minPosts,maxPosts){returnposts.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.

asyncfunctiongetPosts(){constprevPosts=this.state.postsconstlatestPosts=awaitfetch('...')constnextPosts=concat(prevPosts,latestPosts)this.setState({posts:nextPosts})}

Singular and Plurals

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

Stars

Watchers

Forks

Sponsor this project

 

[8]ページ先頭

©2009-2025 Movatter.jp