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) {} // Nao 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) {} // Nao 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
