Naming Rules: one of the hard things in Computer Science

  • To enable code reviews to focus on more important issues than arguing over syntax and naming standards.
  • To enable code quality review tools to focus their reporting mainly on significant issues other than syntax and style preferences.

Potential benefits

Some of the potential benefits that can be obtained by adopting a naming convention include the following:

  • to help formalize expectations and promote consistency within a development team;
  • to enable the use of automated refactoring or search and replace tools with minimal potential for error;
  • to enhance clarity in cases of potential ambiguity;
  • to enhance the aesthetic and professional appearance of work product (for example, by disallowing overly long names, comical or “cute” names, or abbreviations);
  • to help avoid “naming collisions” that might occur when the work product of different organizations is combined (see also: namespaces);
  • to provide meaningful data to be used in project handovers which require submission of program source code and all relevant documentation;
  • to provide a better understanding in case of code reuse after a long interval of time.

Challenges

The choice of naming conventions (and the extent to which they are enforced) is often a contentious issue, with partisans holding their viewpoint to be the best and others to be inferior. Moreover, even with known and well-defined naming conventions in place, some organizations may fail to consistently adhere to them, causing inconsistency and confusion. These challenges may be exacerbated if the naming convention rules are internally inconsistent, arbitrary, difficult to remember, or otherwise perceived as more burdensome than beneficial.

Readability

Well-chosen identifiers make it significantly easier for developers and analysts to understand what the system is doing and how to fix or extend the source code to apply for new needs.

a = b * c;
weekly_pay = hours_worked * hourly_pay_rate;

English language

Use the English language when naming your variables and functions.

/* Bad */
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']
/* Good */
const firstName = 'Gustavo'
const friends = ['Kate', 'John']

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:

  • 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)
https://github.com/kettanaito/naming-cheatsheet#naming-cheatsheet

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
}

set

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

let fruits = 0function 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.

function removeFilter(filterName, filters) {
return filters.filter((name) => name !== filterName)
}
const selectedFilters = ['price', 'availability', 'size']
removeFilter('price', selectedFilters)

delete

Completely erases something from the realms of existence.

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

compose

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

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

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

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']

Thanks for:

📱IMStudio 🎓is a team that doesn’t stop moving. We expound on subjects as varied as developing a software application and through to disruptive technologies.🎓

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store