Home >Web Front-end >JS Tutorial >Variable naming based on clean code

Variable naming based on clean code

Susan Sarandon
Susan SarandonOriginal
2024-12-28 00:49:08422browse

Nomeação de variáveis baseada no clean code

Clean Code is the set of several code conventions that together create a new way of writing your code so that it can be more readable, maintainable, reliable and predictable, promoting efficiency and facilitating teamwork.

One of the several principles of clean code is naming variables with names that are self-describing and self-explanatory to avoid ambiguities and write cleaner codes, a great author  Zeno Rocha said in his book 14 Habits of Highly Productive Developers  we should always write code that our future self can understand even after years. Naming variables with diminutives or abbreviations can lead to different interpretations, especially between developers with different levels of involvement in the project this can lead to future problems.

It is very common that as the code base grows and its variable is left aside there is a need to revisit it in the future and poor writing will make it difficult to understand your code that helps.

examples of bad variables:

const date = new Date()
// Nome da varável é muito genêrica e não explica o que ela é
function getData(req, res) {}
// Nâo descreve bem o dado que ela está requisitando 

examples of good variables:

const currentDate = new Date()
// Nome mais explicativo sobre o que ela é e menos genêrico
function getUserGithubCategory(req, res) {} 
// Descreve melhor o dado que a função está requisitando 

Still in this same logic of writing meaningful variable names, we come to another important point, which would be when writing Boolean variables that follow the same writing direction, but we must use another little rule that accumulates to the previous one.

She says the following, we should write Boolean variables as if they were some kind of question that can be answered with yes or no, this is because Boolean variables can only receive true (yes) or false (no ) and a question to say whether they are active or not helps with code reading.

example without applying the rule:

const ticketPark = user.ticketPark 

if (!ticketPark ) {
  throw new Error('O Marcos não possui um bilhete para entrar no parque!')
}

example with application of the rule:

const hasUserTicket = user.hasTicket // o usuário tem o ticket ?

if (!hasUserTicket) { // se o usuário não tiver o ticket 
  throw new Error('O Marcos não possui um bilhete para entrar no parque!')
}

Do you agree with me that when using this model of naming Boolean variables it doesn't make reading simpler by saying that if the user has the ticket he can go to the ride rather than just checking that the park ticket isn't fake? Using these types of can really improve third-party understanding of your code and help you avoid ambiguities as well.

Finally, we have just one more simple rule that accompanies these last two, which, in addition to writing your code better, is to use variables to store the “magic numbers” in your code. But after all, what are these magic numbers in your code? Generally, many programmers, when applying business rules to their projects, use various numbers to perform some operations in the code and which in turn are thrown into the code without necessarily having any explanation as to why they are there.

example of a code full of magic numbers:

const date = new Date()
// Nome da varável é muito genêrica e não explica o que ela é

can you understand what the code is for?

It’s difficult with these indescribable numbers, right?

have you ever heard this phrase “I don’t know why else if you remove that the code breaks”? It represents well what I want to say here, avoid leaving these numbers loose and without an explanation of why they are there, if it is not possible to make it clear in a variable, make a simple comment. may exist in your code.

Take a look at how this code should be written:

function getData(req, res) {}
// Nâo descreve bem o dado que ela está requisitando 

It’s better now, right?

Benefits

Adopting practices like naming variables clearly, avoiding magic numbers, and following Clean Code principles not only improves the quality of your code, but also makes it easier to collaborate with other developers and maintain in the long term.

Remember: writing clean code is not about achieving perfection, it's about making the code more accessible, understandable, and predictable for everyone who uses it, including you in the future.

Try applying these rules to your next project and notice the difference! Share these tips with colleagues or your team to create a more productive and efficient work environment. After all, well-written code is the first step to building high-quality software.

So, how about starting today? Write code you'll be proud to read in the future!

The above is the detailed content of Variable naming based on clean code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn