Author: Han Grass wechat: HancAO97 introduction: a different north drift programmer, welcome to add wechat criticism and correction, exchange discussion (or blind date) PS: this article may be updated at any time

Study background

** Why do I want to systematically learn about clean code and refactoring? ** This is a very painful and sad story (the following memory) :

In fact, the story is not complicated, except that last year when I just started to work, I took over the debugging of a project and the development of unfinished functions, but the old code made me miserable as a cute new girl. Now to recall that the old code’s faults are actually a little vague, I will simply list them:

  • Weird and magical variable and method naming
  • Proper nouns are not named in agreement
  • Super long methods are everywhere
  • Seven or eight parameters are received and the meanings of the parameter names are ambiguous
  • Several thousand lines of.vue.
  • Extremely deeply hierarchical callback functions
  • Wait, wait, wait. Magic

During that period of time, the construction period was tight, and the code I took over broke a huge number of bugs every day. The old code also made me feel overwhelmed, which made me quite irritable. But I was clever and witty, and I still completed the task successfully. But then I had this idea:

  • I was paranoid that the problems with the previous code had affected my work schedule (it did, I worked overtime a lot…).
  • I want to know what good code looks like, and I want people to be happy when they take over my code!! (No way, this is the sense of responsibility, ha ha ha, secretly shameless boast themselves)

After the end of this project, I came to the new project team full of expectation. After that, it happened that the module I was in charge of was about to be refactored recently, so I took the task of refactoring naturally. This time, I saw that the smelly and long code was no longer impatient, but enthusiastic!!

So in the development and design of drawing a variety of class diagrams, timing diagrams, at the same time, opportunily, take this opportunity to think about what kind of code is good, make this refactoring beautiful! So this refactoring task was also an opportunity for me to learn and think about what good code is!

As a result, the Way to Clean Code, The Complete Code 2, and Refactoring: Improving the Design of Existing Code, the second edition, are on the agenda, of which the Way to Clean Code is one I picked up during the refactoring process, and the other two are more recent. I couldn’t have done it a few books by article summary is very good, I probably will go to mention only a few simple things in the book, but I hope you read my rough shallow article, reviewing these books have a desire to read, to clean the code has their own pursuit, to realize technology is indeed our r&d engineers, Clean code is also one of the most fundamental aspects of our professionalism, something that we need to continue to learn and reflect on ourselves.

Introduction of three books and personal recommendation (as a cargo engineer)

** The Way to Clean Code, Complete Code 2, and Refactoring: Improving the Design of Existing Code ** These three books actually have a lot in common. In fact, whether it is clean code or refactoring, the ultimate goal is the same: to make code better and easier to understand. There are many themes that are consistent in all three books, but each has its own emphasis and depth, so I recommend all programmers to read these three books.

How to Clean Code

I read this book first, and it was really enlightening to me at that time. I just read it briefly, and I felt that I had broken through the process of supervision and supervision. There is a world in details, clean and excellent code, and all the problems I found in Codereview have been provided with authoritative basis here.

As stated in the book’s synopsis, the authors of this book provide a set of proven clean code practices, which are expressed in this book as rules, with pros and cons, that can be followed to write clean code.

Yes, it is so directly, like this sentence, I pass the book on the stand or fall of code with a certain standard, have a certain understanding, and use rules to go on my coding constraints in practice, feeling a lot of ascension, to read this book also to some extent improve the quality of my project code refactoring, ha ha

So, this is one of the first books I recommend to new programmers (like me), and it’s one of the first of the three books I think I should read. The reasons for this recommendation are straightforward: this book is easy to understand, and even a rough, quick read can yield a lot of knowledge. Must be a great help to clean up the code! Just trust me

Codex 2

In fact, The Book “Complete Code 2” is so famous that it is the bible of engineers (at least in our company), and leaders are crazy about it from day one. We probably think is “know, know, master don’t read, we see it!”

Codex 2 is a famous book that doesn’t need much introduction:

  • This book is the definitive guide to the building blocks of software — just the book to take with you if you’re going to a lonely island.
  • For both novice and experienced developers, Codex 2 will teach you the best way to think about programming.
  • And so on…

Almost everyone who has read this book has raved about it, but I’m sorry, I haven’t read much of it yet, and it does cover a lot, a lot:

  • Pseudocode programming
  • Variable names, conditional statements, control loops…
  • Table driven method
  • Test, debug
  • refactoring
  • .

It’s a lot of stuff, it’s like an encyclopedia of software development, but as a front-end developer, I might find some of it difficult to understand, and the volume is huge, so I personally read this book last.

Refactoring: Improving the design of existing code. 2nd edition

This book is also very famous, recently the company is also organizing the collective study of this book, no way I have already started the reading of this book, fast person step, is so powerful, forget it, don’t talk, to the point.

My eyes is like a large directory, this book presents a first case, how to introduce his refactoring, also be into a door, then introduces some reconstruction principle, then introduces the code of bad taste, it is necessary to know this, at least we have to do before refactoring must want to know what’s wrong with this code!), And the importance of building a testing system (you can’t refactor a bunch of bugs). Then there’s a big refactoring index:

  • Refactoring mode name
  • Reconstruction motives
  • Refactoring approach
  • Refactoring example

All subsequent refactorings are described in this format. I’ll explain what the refactoring method is called, why it’s necessary in this case, how to do it, and some examples. Very easy to use! And the second edition of Refactoring: Improving the Design of Existing Code is an example written in JS!!

So we front-end engineers are not very friendly.

The summary of this chapter

The Way to Clean Code, Complete Code 2, and Refactoring: Improving the Design of Existing Code have some things in common, but they focus on different things and go into different levels of depth, so I recommend reading all of them. The order I recommend reading them is:

  1. How to Clean Code
  2. Refactoring: Improving the design of existing code. 2nd edition
  3. Codex 2

Come on, guys

Clean code

Main source: The Way to Clean Code

preface

I’ll give you a brief overview of why we clean code (based on my own experience) and a brief overview of how we can clean code from several dimensions. Be sure to read your own books, I just listed some!

Why clean code?

Software quality, I think you’ll recognize, is not only dependent on architecture and project management, but also closely related to code quality.

There is a concept in “The Way of Clean Code” : the quality of code is directly proportional to its cleanliness. Clean code is not only reliable in quality, but also lays a good foundation for later maintenance and upgrade.

I experienced the baptism of chaotic code in my first project after entering the company, and I have a deep feeling about this. The chaotic code always concealed various bugs [unreliable], and I also suffered great resistance [bad maintenance] in the process of maintenance. I think as long as we both have a high pursuit of clean code, the development of the project will be a very smooth virtuous cycle.

As shown in figure 1 below, the speed and quality of the iteration remained steady.

But if we let the code run wild, we can end up with a situation like this, where development becomes less efficient and of poorer quality. [Use echarts to make the picture, so you know what it means]

The messy code is like nohara Shinosuke cabinet. When we use it, we think nothing, but when we open it!

But here it is!

Yes, I can describe messy code as dangerous. In my eyes, they are unreliable and have all kinds of problems.

How to clean up code

Bjarne: I like elegant and efficient code. The logic of the code should be straightforward, so defects are hard to hide. Minimize dependencies, make it easy to maintain, refine error-handling code according to some hierarchical strategy, optimize performance, and avoid the temptation to do random optimizations, create a mess, and clean code that only does one thing well.

Grady: Clean code is simple and straightforward. Clean code never hides the designer’s intent and is full of neat abstractions and straightforward control statements.

.

Here are some ideas from the masters, and I think that when you see the insights from the masters, you might immediately get the idea that, yes, clean code is direct, simple, and obvious. It can explain the coder’s design idea without concealing it.

In brief, there are the following points:

  • Minimize dependencies for easy maintenance

  • Simple and straightforward, full of neat logical processing and straightforward control statements.

  • All runs pass, with unit and acceptance tests

  • There is no duplicate code

  • Writing code can fully cash out of our design concept (this can be through the class, method, attribute naming, code logic coding clear to reflect. Of course, on the front end, I think we can also divide some components and modules to make the logic clear.)

To me, clean code is code where we find a way to present our ideas simply and directly. How to clean code is to think about how to make our code “simple and direct” process.

Meaningful naming

“As long as the name needs to be supplemented with a comment, it means there is still a problem with our name.”

  • All names have to be meaningful. Names tell you why they exist, what they do, and how they should be used.

Let me give you a code that you might have written when you first went to college

#include <stdio.h> int main(){ printf("Hello, C! \n"); int i = 10; int m = 1; for(int j = 0; j < i; j+=m){ for(int n = 0; n< i-j; n++){ printf("*"); } printf("\n"); } return 0; }Copy the code

If you look at this, it’s all a bunch of I’s, m’s, n’s, j’s and so on, and you don’t know what the variables are for, but what this code actually ends up printing is a right triangle made up of *. But that’s exactly what I did when I was writing code, I, J,m,n, and so on, and there’s nothing semantically involved, name = alphabet. But now it is much more high-end, from the dictionary to find, but also permutation and combination. So getUser, isAdmin, etc., semantic improvement, and we can also intuitively tell what this method is doing, what this variable is doing by naming it.

  • Avoid misleading

The book gives a few examples: Don’t name variables with proper names that shouldn’t be variables, and a set of accounts “accountList” that aren’t of type List is misleading. Named too similar, such as XYZHandlerForAORBORC and XYZControllerForAORBORDORC, who can tell at a glance what ~

  • Make meaningful distinctions

    let fn = (array1,array2) =>{ for(let i =0 ; i<array1.length; i++){ array2[i] = array1[i]; }}

For example, the above distinction between array1 and Array2 is not meaningful. This is just an assignment operation, which could be either sourceArray or DesArray.

Another example of the name: userInfo, userData are this kind of, it is difficult for us to read what the difference between these two, this distinction is not meaningful, it is just the spelling of the word, rather than the semantic difference

  • Use the read name

It starts with the human brain. A large part of our brain is designed to process language. We evolved the capacity for language, and it’s a waste if we don’t use it. Programming itself is a social activity. Imagine a situation where someone asks you how to achieve this requirement and you say I have a (#¥%… &) here’s a long, hard to read class with a name in it (¥%… For example, there is a method named getYMDHMS (obtain year, month, day, hour, minute, second).

  • Use names that can be searched

In the code above, I use I as the variable. If the code is very long, it would be painful for me to keep track of the changes to this I.

Before the old code on all kinds of end, open, show and so on, a file is very long, a search results of a file dozens of, if it is a public variable or public method name is such, it is even more brutal. Hundreds of good brothers came out… Like the picture below, the variables lean in and say, “Yeah, yeah, that’s me! “

  • Meaningful numbers or strings in a program should be replaced with constants for easy lookup

    export const DEFAULT_ORDERBY = '-updateTime'
    export const DEFAULT_CHECKEDNUM = 0
    Copy the code

Like this, to make the code more semantic and easier to focus on (for example, if the requirements change, the above default sorting, by the time of submission, information collection time, etc., you don’t have to look around -updateTime to change the default sorting)

  • Class and object names should be nouns or noun groups, and method names should be verbs or verb groups.

For example, we often use updatexxx, filteredXXX is such a naming convention.

  • Attribute names add the necessary context, but short names are better than long names if they are clear enough to use. Don’t add unnecessary context.

  • There is a word for each concept

For example, before development, we should determine a list of proper nouns, such as tag and label, ticket and workOrder. It will be confusing for readers, which will cause a burden in the future, and may hide some bugs.

function

“The master code is telling a story, not writing a program. “

  • Short: 20 top best

  • The function has to do one thing

  • If,else,while blocks should be one line long (calling other logical functions) and there should be no more than two levels of indentation. Nothing is absolute)

  • Each function is at a level of abstraction

For example, the render method needs the A, B, C of the render child level, so the render method will do the high-level things, A, B, C to the child level method to do.

The code should be read in a top-down order, with higher-level methods at the top and the declaration of the method being called below the declaration of the method.

  • Function parameters as few as possible. (The book “Refactoring” can be used to replace parameters with queries, remove marked parameters, introduce parameter objects, etc., or function currying, etc., but there are many methods.)

  • Use descriptive function names (of course, the shorter and more concentrated the function, the easier it is to name it)

  • Extracting exception handling, i.e., try-catch, is a function that should only do one thing, and error handling is one thing

  • Identifier arguments are ugly, and passing Boolean values to functions is outrageous, to see if calls like renderTab (true) are confusing

  • Verbs and keywords. Function names are verbs, arguments are nouns, and the order is guaranteed. Like saveField (name). AssertExpectedEqualsActual (expected, actual)

  • No side effects, don’t do anything else, like updateUserList, don’t just update the list of users, but also do something else in the method.

  • Repetition is the root of all evil in software. Reject duplicate code

Finally: Writing code is the same as writing an article. Think about what you want to write first, and then polish it. The first draft may be rough and disorderly, but you have to work through it until you get it right. The art of programming has always been the art of language design.

annotation

  • Comments should not be used to beautify bad code

  • The only really good comment is finding a way not to comment at all

  • Good comment:

    Legal information Informative notes Informative notes explain intent

    Annotate warnings (e.g., comment // don’t touch my code!! This is a warning, it is not easy to see here) todo annotation (after marking here to continue to develop), zoom in

  • Bad comments:

    Muttering unwanted comments misleading comments (e.g. “Here the code name was changed, but the comments were not changed”) // The status of the name is used to indicate the name. Compliance type annotation Log type annotation Nonsense comments Terrible nonsense location markers (often used as a child / / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * to tag location…). If you can use functions and variables, don’t comment out code with attribution and attribution HTML comments non-local information too much information, not obvious links

The summary of this chapter

Simple from the variable, method, comment three angles to say how to clean the code, these are also we are more common, in fact, the content is far more than these. Also, clean code requires a habit to be developed from practice. If you have time to go back and look at the code you wrote before, you may feel terrible. At this point, you grow!

Really, come on together ~

refactoring

Main source: Refactoring: Improving the Design of existing Code, part of Codex 2: Refactoring

Author’s note: When programming, follow camp rules to make sure your code base is healthier when you leave than when you arrived. (I’ve been trying to do this for a new project, and it’s critical that we don’t let our code sink with time and version iterations!!)

What is a refactoring

  • Noun: an adjustment to the internal structure of software designed to improve its understandability and reduce the cost of modification without changing its observable behavior.
  • Verb: to adjust the structure of a software without changing its observable behavior, using a series of refactoring techniques.

The key to refactoring is to use a large number of small, behavior-preserving steps to achieve large-scale changes.

Refactoring is similar to performance tuning in many ways: both require code changes, and neither changes the overall functionality of the program. The difference is the purpose: refactoring is to make the code “easier to understand and easier to change.” This can make the program run faster or slower. When it comes to performance tuning, I only care about making the program run faster, and I’m prepared for the possibility that the resulting code will be harder to understand and maintain.

[Note] : Refactoring helps me write faster software. In the short term, refactoring may slow down the software, but it makes it easier to tune software performance during the optimization phase, and ultimately pays off.

Why does refactoring

  • Refactoring improves software design

  • Refactoring speeds up programming

  • Refactoring helps find bugs

  • Refactoring makes the software easier to understand

The sole purpose of refactoring is to allow us to develop faster and create more value with less work.

The point of refactoring is not to polish the codebase to a shine, but to do it purely economically. We refactor because it allows us to do it faster — add features faster, fix bugs faster. It’s important to keep this in mind and emphasize it in your communication with others. Refactoring should always be driven by economics.

When refactoring

  • Preliminary refactoring: Make it easier to add new features
  • Refactoring to help you understand: Make your code more understandable
  • When the codereview refactoring
  • .

There are a lot of them in the book, but for me these three are pretty common.

Here’s a fun example from the book I’ll share with you:

It’s like I’m going 100 kilometers east. Instead of driving east into the woods, I would drive 20 kilometers north onto the highway and then 100 kilometers east. The latter is three times faster than the former. If someone urges you to “go straight there,” sometimes you need to say, “Wait, I’ll look at the map first and find the fastest way.” This is what preparativity reconstructs for me.

Hahaha, this is a fun example, it’s true that refactoring can make things easier

When you shouldn’t refactor

  • If I see a messy piece of code that I don’t need to change, THEN I don’t need to refactor it. If ugly code can be hidden under an API, I can tolerate it remaining ugly. Refactoring is only valuable if I need to understand how it works.

  • If rewriting is easier than refactoring, don’t refactor.

  • Don’t think of refactoring as a synonym for write first, change later! Codex 2

Security refactoring

Code 2

  • Save the initial code
  • Refactor slowly
  • Do only one refactoring at a time
  • Make a list of things to do
  • Use checkpoints
  • To test
  • Add test cases
  • Check for changes to the code
  • Adjust the refactoring approach based on the level of refactoring risk

Tip: Must have the test system as the safeguard!

The bad smell of code

If the diaper stinks, change it.

The purpose of the bad track of our path code is: when should we refactor, why should we refactor the code here, and what’s wrong with the code here?

Here are my most common ones:

  • Mysterious named
  • Duplicate code
  • Overlong function
  • Long parameter list
  • Global data
  • Variable data [how did I think of **Functional programming* * 】
  • Divergent variation [this occurs when a module often changes in different directions for different reasons]
  • If you have to make a lot of small changes in a lot of different classes for every change, you’re going to get the bad taste of shotgun change.
  • Attachment [putting together things that always change together. Data and the act of referring to it always change together.Strive to separate code into regions, maximizing interactions within regions and minimizing interactions across regions.It’s a very romantic name. Why, reading a book and abusing a dog?)

  • Similar classes
  • Too long message chain
  • The versatility of rhetoric
  • Repetition of the switch
  • Redundant elements
  • Some comments are necessary, but…
  • Too much class
  • And so on…

The summary of this chapter

I’m not going to go over a few refactorings here, because there are many, and the rest of Refactorings: Improving the Design of existing Code is a large index that we can scroll through to find the refactorings we need.

Another reason for not simply enumerating this is that I was forced to delete a lot of pictures because I was out of my word limit… uncomfortable

conclusion

Any fool can write code that a computer can understand. The only good programmers are those who can write code that humans can easily understand.

Follow the camp rule: Make sure your code base is healthier when you leave than when you arrived.

In these books, there are many golden sentences like this, and I hope that you can learn and practice to write higher quality, cleaner code, which is the professional quality that we need to have as r&d engineers.

Everyone refueling together, this article also always remind themselves ~

How was the Lantern Festival? Did you see the fireworks?

Where have seaside or riverside fireworks show, really want to see (someone to accompany me) ah ~

After the 15th, the Spring Festival is over. Ah, people who are drifting outside should pay attention to their health. Don’t forget that there are people waiting for you at home.

After I look at the vuE3 source code, look at the algorithm to go, scallion!