- Good Coding Practices — Five Tips to Enhance Code Quality
- Original author: Jay
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: NeoyeElf
- Proofread by: dandyxu, allenlongbaobao
Good Coding Habits – 5 tips for Improving Code Quality
Good coding practices are like a beacon in the dark night, guiding lost developers safely to shore. Good code is predictable and easy to debug, extend, and test.
Good coding habits can make your colleagues more productive while making your code base as a whole a pleasant reading experience.
I’m going to share with you five general good coding habits that can improve the readability, extensibility, and overall quality of your code. The sooner you understand and apply these principles, the greater your benefits.
Let’s get started.
Why good coding habits?
Learning and applying good coding habits is like investing in stocks that you know will grow exponentially. In other words, if you make a one-time investment now, the benefits and returns over the next few years or even months will far exceed what you put in now.
Developers at any stage of their career can benefit from applying and learning good coding habits. As I said above, the sooner you start using them, the better off you will be. Now is the perfect time to learn and apply good coding habits to your current project.
I make these points so that they support each other and make sense both individually and in combination.
1. Name methods and variables succinctly
When naming classes, variables, and methods, it’s tempting to name them in our own way. Especially if you think it all makes sense. Try to go back to the code a few months later and see if it still makes sense. If so, you probably named your variables and methods wisely at the time.
The method name is similar to the title and sentence in the article.
Therefore, when naming a method, you should be able to accurately summarize the content of the method. If the method name becomes too long or vague, the method is doing too many things.
The contents of a method make up the method name.
When you read a passage, what stands out most to you? Usually, the headline stands out. In a program, key methods are like headings. When you write a submission for a high school or college essay, do you just throw in a few lines and write the headline without thinking?
A simple and intuitive way to read thousands of words.
Of course, the choice of words in a sentence and how they are put together is also important. This is why we also need to name our variables deliberately. In most cases, before looking at the code logic, one will try to get an overview of the implementation details by reading the variable names in each line.
Make sure method and variable names are clear and describe exactly what is happening. Imagine how angry and confused a tourist would be if you gave him or her the wrong directions. You’re showing the way to the next programmer who comes to read your code.
2. Minimize the use of global variables
No matter what language you use, you probably hear this a lot in programming. People say that using global variables is bad, but don’t explain why. So let me tell you why you should minimize and avoid global variables as much as possible.
Global variables can be confusing because they can be accessed anywhere in the program.
If global variables are also mutable, this can add to the confusion. If you declare a variable, chances are you just want to use it in your own code. What do you think will happen next?
Here’s a basic example written in JavaScript, but the following code should be easy to understand no matter what programming language you’re using.
var GLOBAL_NUMBER = 5;
function add(num1) {
return num1 + GLOBAL_NUMBER;
}
Copy the code
For this function, even if we pass num1 = 3, we can’t be sure that the method will return 8 because other parts of the program may have changed the GLOBAL_NUMBER value.
This increases the likelihood of side effects, especially if we use multithreaded programming. To make matters worse, the complexity of a program is proportional to the amount of code.
Using a single global variable in 100 lines of code is manageable. But imagine if that project had evolved into a 10,000-line project. There are many places in the project where you can modify this variable. Also, other global variables may have been added to the code by now.
Maintaining code is now a nightmare.
If possible, find ways to eliminate global variables. Global variables make every developer’s job harder.
3. Write predictable code
If you follow my blog, you might notice that I like pure functions. In particular, if you’re a beginner, I implore you to try writing clean code. Let me tell you four things you need to follow when writing code.
Avoiding state sharing (EMM… Global variables). Keep the function clean. In other words, functions, classes, and subroutines should all have a single responsibility.
If your job is to cook rice, cook rice and do nothing else to avoid confusing your colleagues. Don’t do anything you shouldn’t.
Code with predictable results is like a vending machine. You put the money in and press the coke button. You know you can get a coke for your money. This rule also applies to coding. Make the coding result predictable. A good coding habit is to write code with predictable results.
Imagine if you put money into a vending machine and press the coke button, but instead, the vending machine gives you fanta. Unless you like surprises, or you don’t care what you drink, you won’t be happy.
Without exception, developers don’t like to be surprised by the side effects of bad code.
Let’s look at a very simple example.
function add(num1, num2) {
return num1 + num2;
}
Copy the code
The simple add function above is pure. It produces predictable results. No matter what environment you use it in, no matter what global variables, if you type in 1 and 2, you always get 3.
// This will never equal a value
// other than three
add(1, 2);
Copy the code
4. Write reusable code
I tried modular coding so THAT I could simply import the module without having to rewrite it. It’s better than reinventing the wheel, if you can keep the module simple, you’ll reduce bugs and side effects.
Most of all, I want you to understand why we like to stick to these principles.
Code is reusable when it can be ported to another development environment and seamlessly integrated into Tweets.
Keep in mind that you are not (or at least shouldn’t be) the only one writing and maintaining the code base. Building on points 1, 2, and 3 leads us to point 4, which is writing reusable code. In other words, steps 1-3 help us write reusable code. Let’s review why steps 1-3 can help developers write reusable code.
- The simplicity of methods and variable names makes the code more acceptable to other developers.
- Reusable code should not depend on global state. Code that uses dependent libraries is often classified as hard-to-reuse code.
- Reusable code should produce consistent results independent of mutable state.
When writing code, try asking yourself, “Can I (or do I want to) reuse this code in another project?” . This will help you write reusable code that is more valuable.
5. Write unit tests
You’ve probably heard this many times, because unit tests make code more mature and robust. Because of project time constraints, unit testing is one of those good coding habits that gets lost in favor. Project managers and customers want immediate results.
Code with unit tests is like a Chinese bamboo tree. The results may not be obvious at first, but as long as you are patient, the benefits will be obvious and well worth it at the right time!
For the first four years, Chinese bamboo growth was limited. Like any other plant, it needs to be cultivated. In its fifth year, it grew 80 feet in just six weeks.
While it may not take that long to reap the benefits of unit testing, the patience of both you and your project manager will often be tested. Of course, if you take the time to write these unit tests and focus on code quality, the quality and robustness of your code will be greatly improved. All of this effort ultimately translates into a better user experience and more extensible code with minimal side effects.
If you are not allowed to write unit tests in your working code, try to get into the habit of writing unit tests in your personal projects. Many companies see value in writing unit tests, which can be a very useful skill.
More important than this skill is the ability of unit testing to broaden the developer’s view of the big picture and examine all possible scenarios.
Consider the possibilities of these scenarios to weigh the pros and cons and add the appropriate number of valid check cases. Make assumptions and redesign the code.
All that blood, sweat, and tears will eventually converge into beautiful, tested, pure robust code. It’s reusable, predictable, and likely will serve you well in your future work.
The knowledge you gain from reading this article will at least help you become a mature programmer.
Complete listing
If you have other, better coding habits that you’d like me to add to this list, or if you feel an important point is missing from the list, please leave a comment below. I will add your comments to this list as soon as possible.
Happy Coding!
About the authorJay
I am a programmer currently living in Seoul, Korea. I created this blog to express what I already know and what I’m learning in the form of articles to accumulate knowledge and to help build a wider community. I love data structures and algorithms and specialize in the back end and databases.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.