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

Variable naming based on clean code

Dec 28, 2024 am 12:49 AM

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 é
Copy after login
Copy after login
function getData(req, res) {}
// Nâo descreve bem o dado que ela está requisitando 
Copy after login
Copy after login

examples of good variables:

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

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!')
}
Copy after login

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!')
}
Copy after login

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 é
Copy after login
Copy after login

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 
Copy after login
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles