All Projects → kettanaito → Naming Cheatsheet

kettanaito / Naming Cheatsheet

Licence: mit
Comprehensive language-agnostic guidelines on variables naming. Home of the A/HC/LC pattern.

Projects that are alternatives of or similar to Naming Cheatsheet

abbreviations-in-code
List of common abbreviation in program codes
Stars: ✭ 163 (-98.28%)
Mutual labels:  naming, naming-conventions, cheatsheet
CSharpNamingGuidelines
C#命名规范中文版/C#编码规范中文版
Stars: ✭ 30 (-99.68%)
Mutual labels:  naming-conventions, guidelines, naming-schemes
VF-BlenderAutoSaveRender
Automatically saves a numbered or dated image after every render and can extend the Blender output path with dynamic variables
Stars: ✭ 34 (-99.64%)
Mutual labels:  naming, naming-conventions
Patterns Cheatsheet
Software design patterns cheatsheet.
Stars: ✭ 47 (-99.5%)
Mutual labels:  cheatsheet, pattern
Globbing
Introduction to "globbing" or glob matching, a programming concept that allows "filepath expansion" and matching using wildcards.
Stars: ✭ 86 (-99.09%)
Mutual labels:  cheatsheet, pattern
android-convention-cheatsheet
Android Naming Convention Cheat Sheet
Stars: ✭ 52 (-99.45%)
Mutual labels:  naming, cheatsheet
Apex-Code-Conventions
Apex conventions and best practices for Salesforce Developers
Stars: ✭ 28 (-99.7%)
Mutual labels:  naming, naming-conventions
Coding-Standards
Coding Guidelines for C#
Stars: ✭ 125 (-98.68%)
Mutual labels:  naming-conventions, guidelines
Awesome Cheatsheets
超级速查表 - 编程语言、框架和开发工具的速查表,单个文件包含一切你需要知道的东西 ⚡
Stars: ✭ 7,930 (-16.31%)
Mutual labels:  cheatsheet
Cheatsheet Docker A4
📖 Docker CheatSheets In A4
Stars: ✭ 32 (-99.66%)
Mutual labels:  cheatsheet
Ts Pattern
🎨 A complete Pattern Matching library for TypeScript, with smart type inference.
Stars: ✭ 854 (-90.99%)
Mutual labels:  pattern
Magit Cheatsheet
Stars: ✭ 13 (-99.86%)
Mutual labels:  cheatsheet
Llvm Cheatsheet
LLVM, clang, ninja, dyld and others.
Stars: ✭ 36 (-99.62%)
Mutual labels:  cheatsheet
Active Directory Exploitation Cheat Sheet
A cheat sheet that contains common enumeration and attack methods for Windows Active Directory.
Stars: ✭ 870 (-90.82%)
Mutual labels:  cheatsheet
Minisauras
An open-source CI/CD automation tool based on GitHub Actions that pulls all the JavaScript and CSS files from your base branch, minify them and creates a pull-request with a new branch.
Stars: ✭ 40 (-99.58%)
Mutual labels:  action
Flutter realworld example app
Work in progress...
Stars: ✭ 12 (-99.87%)
Mutual labels:  pattern
Analysissummary
Vorlesung Analysis für Informatiker WS16/17 an der TUM
Stars: ✭ 10 (-99.89%)
Mutual labels:  cheatsheet
Github Action Get Previous Tag
Get the previous tag
Stars: ✭ 42 (-99.56%)
Mutual labels:  action
Yoctoproject Cheatsheet
One-Stop Repository for all that wish to skim through or deep-dive into Yocto Project
Stars: ✭ 39 (-99.59%)
Mutual labels:  cheatsheet
Extending Tea
Example of an extension to The Elm Architecture
Stars: ✭ 30 (-99.68%)
Mutual labels:  pattern

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 */
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']

/* Good */
const firstName = 'Gustavo'
const friends = ['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

Pick one naming convention and follow it. It may be camelCase, 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 */
const page_count = 5
const shouldUpdate = true

/* Good */
const pageCount = 5
const shouldUpdate = true

/* Good as well */
const page_count = 5
const should_update = true

S-I-D

A name must be short, intuitive and descriptive:

  • 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 */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural
const shouldPaginatize = a > 10 // Made up verbs are so much fun!

/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively

Avoid contractions

Do not 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 */
const onItmClk = () => {}

/* Good */
const onItemClick = () => {}

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.

class MenuItem {
  /* 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 */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />

/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={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.

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, shouldUpdateComponent means you are about to update a component, while shouldComponentUpdate tells you that component 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.


Actions

The verb part of your function name. The most important part responsible for describing what the function does.

get

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

function getFruitCount() {
  return this.fruits.length
}

See also compose.

set

Sets a variable in a declarative way, with value A to value B.

let fruits = 0

function setFruits(nextFruits) {
  fruits = nextFruits
}

setFruits(5)
console.log(fruits) // 5

reset

Sets a variable back to its initial value or state.

const initialFruits = 5
let fruits = initialFruits
setFruits(10)
console.log(fruits) // 10

function resetFruits() {
  fruits = initialFruits
}

resetFruits()
console.log(fruits) // 5

fetch

Request for some data, which takes some indeterminate time (i.e. async request).

function fetchPosts(postCount) {
  return fetch('https://api.dev/posts', {...})
}

remove

Removes something from somewhere.

For example, if you have a collection of selected filters on a search page, removing one of them from the collection is removeFilter, not deleteFilter (and this is how you would naturally say it in English as well):

function removeFilter(filterName, filters) {
  return filters.filter((name) => name !== filterName)
}

const selectedFilters = ['price', 'availability', 'size']
removeFilter('price', selectedFilters)

See also delete.

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 a deletePost action, not removePost.

function deletePost(id) {
  return database.find({ id }).delete()
}

See also remove.

compose

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

function composePageUrl(pageName, pageId) {
  return (pageName.toLowerCase() + '-' + pageId)
}

See also get.

handle

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

function handleLinkClick() {
  console.log('Clicked a link!')
}

link.addEventListener('click', handleLinkClick)

Context

A domain that a function operates on.

A function is often an action on something. It is important to state what its operable domain is, or at least an expected data type.

/* A pure function operating with primitives */
function filter(list, predicate) {
  return list.filter(predicate)
}

/* Function operating exactly on posts */
function getRecentPosts(posts) {
  return filter(posts, (post) => post.date === Date.now())
}

Some language-specific assumptions may allow omitting the context. For example, in JavaScript, it's common that filter operates on Array. Adding explicit filterArray 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 (usually boolean).

const color = 'blue'
const isBlue = color === 'blue' // characteristic
const isPresent = true // state

if (isBlue && isPresent) {
  console.log('Blue is present!')
}

has

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

/* Bad */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0

/* Good */
const hasProducts = productsCount > 0

should

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

function shouldUpdateUrl(url, expectedUrl) {
  return url !== 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.
 */
function renderPosts(posts, minPosts, maxPosts) {
  return posts.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.

function fetchPosts() {
  const prevPosts = this.state.posts

  const fetchedPosts = fetch('...')
  const nextPosts = concat(prevPosts, fetchedPosts)

  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 */
const friends = 'Bob'
const friend = ['Bob', 'Tony', 'Tanya']

/* Good */
const friend = 'Bob'
const friends = ['Bob', 'Tony', 'Tanya']
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].