- English language
- Naming convention
- S-I-D
- Avoid Shortened Words
- Avoid context duplication
- Reflect the expected result
- Naming functions
- Singular and Plurals
- Conclusion
Naming things in programming can be a challenging task, but it’s a crucial part of writing clear and maintainable code. This CheatSheet aims to simplify the process and provide practical tips that can be applied to any programming language.
Throughout the article, we’ll use JavaScript examples to demonstrate these concepts in action.
English Language
Use English language when naming your variables and functions.
/* Bad */ const numAmigos = 3; const colorFavorito = 'rojo'; function saludarAmigo(nombre) { console.log(`¡Hola, ${nombre`}!); } /* Good */ const numFriends = 3; const favoriteColor = 'red'; function greetFriend(name) { console.log(`Hello, ${name`}!); }
By using English language names for variables and functions, the code becomes more accessible and easier to understand for developers worldwide. This makes collaboration and maintenance of the codebase more efficient in the long run.
Naming Convention
Choose a consistent naming convention, such as camelCase, PascalCase, snake_case, or anything else, as long as it remains consistent. Different programming languages may have their own naming conventions, so be sure to check the documentation or popular repositories on Github for guidance.
/* Bad */ const num_items = 10 const shouldDelete = false /* Good */ const numItems = 10 const shouldDelete = false /* Good as well */ const num_items = 10 const should_delete = false
S-I-D
Select the names that are 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 b = ['apple', 'orange', 'banana']; // "b" could mean anything const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural const shouldPaginatize = a > 10 // Made up verbs are so much fun! /* Good */ // Add descriptive variable names improve readability const postCount = 5 const fruits = ['apple', 'orange', 'banana']; const hasPagination = postCount > 10 const shouldPaginate = postCount > 10 // alternatively
Avoid Shortened Words
Using abbreviations or contractions can reduce the clarity of your code, so it’s best to avoid them in variable and function names. Although it may be challenging to come up with a concise yet descriptive name, it’s essential to do so for readability and maintainability of your code.
/* Bad */ const msg = 'Ur accnt has been locked'; const usrNm = 'jdoe123'; const numFlds = 5; /* Good */ const message = 'Your account has been locked'; const username = 'jdoe123'; const numberOfFields = 5;
Avoid context duplication
Remove redundant context from variable and function names to keep them shorter and more readable.
class ShoppingCart { /* Method name duplicates the context (which is "ShoppingCart") */ handleShoppingCartOpen = () => { ... } /* Reads nicely as `ShoppingCart.open()` */ open = () => { ... } }
Reflect the expected result
It’s important to choose a name that reflects the expected result of the code.
/* Bad */ const isTallEnough = height >= 48; return isTallEnough ? 'You can ride the rollercoaster' : 'Sorry, you are too short'; /* Good */ const canRideRollercoaster = height >= 48; return canRideRollercoaster ? 'You can ride the rollercoaster' : 'Sorry, you are too short';
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 /fetch | User | ||
getUserMessages | get /fetch | 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 itself, and you are only controlling when it should update. In other words, high context emphasizes the meaning of a variable.
Actions
The verb part of a function name is the action that the function performs. It describes what the function does and helps programmers and users understand its purpose.
get
Accesses data immediately (i.e. shorthand getter of internal data).
const getRandomNumber = function() { return Math.random(); };
You can use get when performing asynchronous operations as well:
async function getUser(id) { const response = await fetch(`/api/user/${id}`); const user = await response.json(); return user; }
set
Sets a variable in a declarative way, with value A
to value B
.
let count = 0; function setCount(nextCount) { count = nextCount; } setCount(5); console.log(count); // 5
reset
Sets a variable back to its initial value or state.
const initialCount = 5; let count = initialCount; function setCount(nextCount) { count = nextCount; } setCount(10); console.log(count); // 10 function resetCount() { count = initialCount; } resetCount(); console.log(count); // 5
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)
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() }
remove or delete?
To choose between “remove” and “delete,” consider their opposite actions – “add” and “create.” “Add” requires a destination, while “create” does not. Use “remove” when undoing an “add,” and use “delete” when undoing a “create.”
compose
Can describe the action of creating new data from existing data. This is often applicable to strings, objects, or functions.
function composeArticleUrl(articleTitle, articleId) { return articleTitle.toLowerCase() + '-' + articleId; }
handle
Can describe the action of performing an action or responding to an event, such as in a callback method.
function handleFormSubmit(event) { event.preventDefault(); console.log('Form submitted!'); // Additional logic for handling the form submission } form.addEventListener('submit', handleFormSubmit);
Context
The “context” of a function refers to the domain or object that the function operates on.
It’s important to define the context or expected data type of a function, as a function is often designed to perform an action on something specific. By specifying the context, it helps to clarify the purpose and usage of the function.
/* A function operating on a specific object type */ function calculateCircleArea(circle) { const area = Math.PI * circle.radius ** 2; return area; } /* A function operating on a specific data type */ function findMax(array) { return Math.max(...array); } /* A function operating on a specific DOM element */ function hideElement(element) { element.style.display = "none"; } /* A function operating on a specific API endpoint */ async function getUser(userId) { const response = await fetch(/api/users/${userId}); const user = await response.json(); return user; }
Prefixes
Prefix enhances the meaning of a variable. It is rarely used in function names.
is
Used to indicate that the variable returns a boolean value based on a condition.
const age = 18 const isAdult = age >= 18 // characteristic const hasID = true // state if (isAdult && hasID) { console.log('You can enter the club!') } const temperature = 25 const isHot = temperature > 30 // characteristic const isSummer = true // state if (isHot && isSummer) { console.log('It's hot outside!') }
has
Used to describe if the current context has a specific value or state, usually in the form of a boolean.
/* Bad */ const hasStudents = studentsCount > 0; const areStudentsAvailable = studentsCount > 0; /* Good */ const studentsExist = studentsCount > 0;
should
A function that includes a positive conditional statement, usually expressed as a boolean, along with an associated action.
function shouldDisplayError(statusCode) { return statusCode >= 400 && statusCode <= 599; }
min/max
“Min” and “max” refer to the minimum and maximum values of a range, often used to describe boundaries or limits.
/** Calculates the sum of an array of numbers between the given minimum and maximum indexes. */ function sumRange(numbers, minIndex, maxIndex) { return numbers.slice(minIndex, maxIndex + 1).reduce((acc, curr) => acc + curr, 0); }
prev/next
Indicate the previous or the next state of a variable in the current context. Used when describing state transitions.
function paginateList(list, page, pageSize) { const startIndex = (page - 1) * pageSize const endIndex = startIndex + pageSize const prevPage = page > 1 const nextPage = endIndex < list.length return { prevPage, nextPage, items: list.slice(startIndex, endIndex) } }
Singular and Plurals
Variable names can be in singular or plural form depending on whether they store a single value or multiple values, similar to using a prefix.
/* Bad */ const items = { name: 'Book', quantity: 1 } const item = [ { name: 'Book', quantity: 1 }, { name: 'Pen', quantity: 3 }, ] /* Good */ const item = { name: 'Book', quantity: 1 } const items = [ { name: 'Book', quantity: 1 }, { name: 'Pen', quantity: 3 }, ]
Conclusion
A good variable name can provide a lot of information about its purpose and usage. It should be descriptive, concise, and easy to understand. Use prefixes to enhance the meaning of a variable, specify context or expected data type of a function, use singular or plural names for single or multiple values, and reflect a positive conditional statement when appropriate. Avoid using generic names or abbreviations, and use clear and consistent naming conventions. By following these guidelines, you can write more readable and maintainable code.
Thank you for reading !!!
If you have any more questions or need further assistance, don’t hesitate to ask!
I must show some appreciation to the writer for bailing me out of this type of scenario. As a result of exploring throughout the the net and obtaining suggestions that were not productive, I thought my life was done. Living minus the solutions to the problems you’ve solved by means of your entire site is a critical case, and the ones which may have adversely affected my entire career if I had not come across your web site. Your good mastery and kindness in taking care of a lot of stuff was useful. I don’t know what I would’ve done if I hadn’t encountered such a stuff like this. I can also at this point look forward to my future. Thanks so much for the skilled and result oriented guide. I won’t think twice to recommend the website to anyone who desires guide about this problem.
Thanks for another magnificent article. The place else may just anybody get that kind of information in such an ideal way of writing? I’ve a presentation subsequent week, and I’m on the search for such info.
Real fantastic visual appeal on this web site, I’d value it 10 10.
Hi there! I simply want to give an enormous thumbs up for the nice data you could have here on this post. I can be coming back to your weblog for extra soon.