preface

If you want to be a better programmer, if you’re not satisfied with the quality of your code, if you don’t want your code to become part of a mountain of shit, read this article and practice it over and over again.

Clean code is what every programmer is after. When you see a file with thousands or even tens of thousands of lines of code filled with a, B, C, D, E, AND F variables and functions, is it just FXXK over and over again? If you don’t want your code to be made fun of, this article will help you understand why junk code is produced, what clean code is, and how to write clean code. Of course, the most important thing is for you, because clean code requires careful practice.

A programmer who writes clean code is like an artist who can turn a whiteboard into a system of elegant code with a series of transformations. The Code Clean Way

Why is junk code produced

When we review code, we encounter the reasons for the junk code, usually have the following situations:

  • Start development before the requirements are clear:

    It goes without saying that programmers are bored with changing requirements, and if you start development blindly before you have a full understanding of the requirements, you’re likely to end up with a product that isn’t what users want, and you’ll end up changing code. As the number of changes increases, you can expect that maintainability and readability will quickly become a challenge.

  • With code running as the ultimate goal:

    This is a mistake many programmers make, assuming that the code has successfully met the requirements of the moment and that everything looks fine. Until we get new requirements, we don’t put any more effort into this piece of code. But remember, the ancestral mountain of shit also always runs, so how do we feel when we try to maintain it?

  • Casual mentality:

    Most of the time, we write code with the mentality of “my boss gave me this requirement, so I’ll C/V it”, even though we know the code can be reused, but our casual mentality allows us to do the C/V mechanically over and over again. Until one day, the requirements change, find the code scattered in various files, and make changes one by one, and if you miss one, mention a BUG.

Definition of clean code

In the Book The Code Clean Way, several gurus offer these conclusions:

  • Elegant and efficient:

    Elegant, efficient code should be pleasant to read, like a well-designed work of art that makes people smile.

  • Simple and direct:

    Clean code should be simple and straightforward, allowing people to see what the code is telling them, without having to guess the intent of the code.

  • Clean code should be readable and supplemented by developers other than the author:

    When we look back at the code we’ve written, have we ever been unable to understand the meaning of the code and the logic behind it? Clean code should be readable and be able to add new code to fulfill requirements as they are added or changed, rather than stacking the code by modifying existing code.

  • Clean code always looks like it was written by someone who really cares:

    Why do we care about our code? When others review our code, we can only praise it because there is hardly any better solution even if we want to improve it. Only with the mentality of caring about the code, to make the code more excellent, let a person praise.

As we can see, the best things about clean code are readability and maintainability. If writing code that makes machines run is a prerequisite for a programmer, then writing code that is readable, even enjoyable, is what a good programmer should strive for. Readability makes code easy to maintain, and clean code helps developers make required changes at a lower cost.

How to clean code

Gradually improve

Writing good code, like writing, is a step-by-step process. To write an article, you need to have a draft first, and then go through time and time again to write an article that satisfies you and your readers. The same goes for code. We can’t just write clean code, so we need to constantly think about what’s missing and make improvements. It’s not dirty code that’s scary, it’s the wrong mindset. No one can write neat code, but it’s important to start with the smallest details and work your way up.

I want to emphasize the importance of increments, because if you change too much at once, you’re likely to end up with unexpected problems in your code that you’ll find difficult to troubleshoot later, and you’ll have to give up. So the range of adjustment to be small, even a variable name modification, a method parameter adjustment, need to be vigilant.

Boy Scout rule

The Scout code is based on a simple rule from the Boy Scouts of America: Camp should be cleaner than it was when they arrived. Borrowing into code requires that we make the code cleaner than it was before we changed it. It doesn’t have to be a lot of work, it might just be changing a variable name, tweaking function parameters, and solving some repetitive code. In short, when we walk away from a piece of code, it should be closer to clean code.

The test code

With tests, you don’t have to worry about making changes to your code! Without testing, every change could be flawed, and there would always be a fear of unforeseen problems. What is the most important thing about test code? That must be readability. The test code needs to be clear, concise, and expressive.

Five rules to follow for clean testing:

  • Fast: Tests should be fast enough. To run tests frequently.
  • Independence: Tests should be independent of each other. One test should not set conditions for the next.
  • Repeatable: Tests should be repeatable in any environment.
  • Self-contained validation: Tests should have Boolean output.
  • Timely: Tests should be written in a timely manner.

Common scenarios for clean code

Name variables with meaningful and commonly used words:

// bad
const yyyymmdstr = moment().format('YYYY/MM/DD');
// good
const currentDate = moment().format('YYYY/MM/DD');
Copy the code

Name each constant:

// bad
setTimeout(blastOff, 86400000);
// good
const MILLISECOND_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECOND_IN_A_DAY);
Copy the code

No more than two parameters:

// bad
function createMenu(title, body, buttonText, cancellable) {
  // ...
}
// good
function createMenu({ title, body, buttonText, cancellable }) {
  // ...
}
createMenu({
  title: 'Foo'.body: 'Bar'.buttonText: 'Baz'.cancellable: true
});
Copy the code

Do only one thing:

// bad
function emailClients(clients) {
  clients.forEach((client) = > {
    const clientRecord = database.lookup(client);
    if(clientRecord.isActive()) { email(client); }}); }// good
function emailActiveClients(clients) {
  clients
    .filter(isActiveClient)
    .forEach(email);
}
function isActiveClient(client) {
  const clientRecord = database.lookup(client);    
  return clientRecord.isActive();
}
Copy the code

Encapsulating conditional statements:

// bad
if (fsm.state === 'fetching' && isEmpty(listNode)) {
  // ...
}
// good
function shouldShowSpinner(fsm, listNode) {
  return fsm.state === 'fetching' && isEmpty(listNode);
}

if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
  // ...
}
Copy the code

There are only a few common tips for clean code listed above, but you can also see the links at the bottom of this article for more tips.

tool

If you want to check code cleanliness, try the following tools:

  1. SonarQube: SonarQube Empowers all developers to write cleaner and safer code.
  2. DeepScan: Make Your JavaScript Better;
  3. Codacy: Automate code reviews on your commits and pull requests;

conclusion

This article introduces you to:

  1. Why junk code is generated;
  2. What is clean code;
  3. How to clean code;
  4. Common tips for clean code;

Thank you for reading this article and I hope it gives you a little inspiration. However, this article can only give you the theoretical basis, to write clean code, is more important in the future development of practice. Finally, I would like to quote liu Xiang of the Han Dynasty from his book “Shuoyuan · Political Theory” :

Seeing is better than hearing; Practice is better than sight; The hand is better than the foot. — Liu Xiang in The Han Dynasty

Recommended reading

The Code Clean Way

Refactoring: Improving the Design of Existing Code

Simplicity of JavaScript code

Seven top-level static code analysis tools