Thoughts after reading "The Way to Clean Code"

Preface

Many times, we see some old code and think it’s incredible. How can there be such a bad code? You will think who wrote such a messy code (sometimes you will be surprised to find yourself), and then you can only Just bite the bullet and read what these codes mean, and then carefully modify one of them to let your work complete, then submit, over.

In this way, the code slowly decays in each submission, and eventually becomes stinking, and then it may even cause some potential vulnerabilities and crises (I have heard that some companies fail because the project code is really unmaintainable. Up).

Therefore, the care of the code is too important. Many people think that it is enough to make the code "work" and then start the next task. In fact, writing code is very similar to writing articles, reports, etc. At first, you write out what you want to express, and then slowly consider and deliberate until you achieve what you want.

Introduction

The book "Clean Code", from the simplest code sequence, variable naming optimization, to mode, system optimization and other aspects put forward some suggestions and solutions, so that the code looks more concise and easy to read. In the last chapter, the author lists his code tidy and optimization experience in the work process completely, which can be regarded as the overall summary of this book. If you don’t want to read the previous chapter, you can get some information directly by looking at Chapter 17. Point, it's just not very detailed. Moreover, the first two chapters are to get the complete project code step-by-step practical optimization process, and decompose the author's entire thought process. It is actually quite interesting to follow, and I can better understand some of the things the author said in the previous chapters.

Code optimization

Next, let’s go over some points that I think are more inspiring and feel better for me.

name

The first is naming. A good name is very important. Think about why when we choose our own name, our parents want to break our heads, or spend money to give us a nice, nice and recognizable name. Similarly, our variable names and method names , Class name, file name, etc., be sure to spend more time thinking about how to get it, it is best to be able to see what this means at a glance.

private BroadcastReceiver mBroadcastReceiver;
private PublicNotifyReceiver mReceiver

Like these two, when looking at the code, huh? What kind of broadcast is this, and then you can only look at the defined place to see what broadcasts it has registered to receive, and the naming of these two variables is actually meaningless, and there is no indication of what it is doing. use! If you replaced appSettingChangeBroadcastReceiverand dialogPushBroadcastReceiverthen? So can we just look at the name and know that the first one is the broadcast of "application settings changes", and the second one is the broadcast of "pop-up push monitoring"? Choose a good name to save the confusion when reading the code, why not do it. So, let the name have a precise meaning .
Let’s look at a naming again getHour(Calendar calendar). This is a method in a tool class, but I can’t see what it is for. At first I thought it was to get the hour field of this Calendar, and I thought about getting the current time. In fact, , It has obtained HH:mmsuch a formatted time string. So its name is not the same as what it does. On the one hand, we have to click in to know what’s done inside. On the other hand, even if such a function exists, when we habitually want to use a The method of this function, as a result, from the method name, there is no such method, and then I wrote a new one. Isn't this a duplicate? so, make the name meaningful, and make them the same, the name and what they do are consistent .

Comment

In the process of writing code, we will write a lot of comments, and there are many things to pay attention to when writing comments, not just casually.

  • Comment only when necessary

It is not necessary to write comments everywhere. We only need to indicate why we write them in some places that are more complicated or have special functions.

  • Don't write nonsense
    /**
     * 日期格式 -- yyyy年
     */
    public static final String DATE_FORMAT_Y = "yyyy年";
    /**
     * 日期格式 -- yyyy年MM月
     */
    public static final String DATE_FORMAT_Y_M = "yyyy年MM月";

For example, we know at a glance what it is. Why do we waste so many lines to write comments? With this energy, we can think better about naming. Many variables and methods can actually be named directly to tell readers what they are doing. There is no need to write comments on everything .

  • Note format
/**
 * <b>Project</b> <i>almanac</i><br>
 * <b>Create Date</b> <i>2014/10/18</i><br>
 * <b>Author</b> <i>***</i><br>
 * <b>Email</b> <i>***@mmclick.com</i><br>
 * <b>Update Date</b> <i>2014/10/18 14:49</i><br>
 * <b>Last Update</b> <i>***</i><br>
 * <b>Description</b> <i>
 * <p/>与时间有关的工具类
 * </i>
 */
public class TimeUtils {
...
}

Look at this comment on the class name, it really looks particularly uncomfortable! First, mix html language comments in the java code. Maybe you would say that it will be very standardized when exporting doc, but in fact, doc is not exported very much, and, most of the time, we still use ide or text editor To read this code, and then the various tags are mixed together, causing great inconvenience to reading, this format is simply too headache.
Second, the comments are all useless things. The current version management tool can record a lot of information for us, including the creator of the class, the creation time, and the update time. This is completely unnecessary in the comments.
Third, the description is redundant. We generally see those ending with Utils and know that this indicates that it is a tool class, TimeUtils, that is, time-related tool class. Then, what is the role of the above description?

Don't write repetitive code

Don't write repetitive code, don't write repetitive code, don't write repetitive code, extract and encapsulate some codes that are used in multiple places. This is not much to say, it is very simple and very important.

function

The first is the amount of function code . Normally, the function displayed on one screen of our editor is generally about 30-40 lines. We should control the function to end within one screen to make the function short and concise.
Single responsibility . We should try our best to let a function do only one thing, and don't let too many functions be mixed in one function. If you do a lot of things, you must name the function properly. You can't name the entire function after one of the functions.
Don't have too many parameters . The most ideal number of parameters is zero, followed by one, then two, and three should be avoided as much as possible. There are enough special reasons to use more than three parameters.
Function order . When we read the code, it is often from top to bottom, so when we write functions, we should also pay attention to the function that appears first, and other functions are called in the function, then follow it, look at the code like this No need to jump around, who am I, where I am, where I want to go back...
For example, an onCreate method in my Activity, you can first see what is done in it at a glance, and then follow the order of execution one step at a time Looking down one step, there is no need to jump anywhere in the whole process, and you can know what my processing flow is like after entering the page.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alc_activity_home_layout);
        linghitSecurityCheck();
        initView();
        initWork();
        addDialogs();
        initAfterUiShow();
        handleDelayTask();
    }

Function sequence (press Ctrl+F12 to appear)
WX20200111-214240@2x.png

design

The design of the entire code structure does not say how complicated the design must be. The key is to be easy to use and easy to read. But this is also based on the accumulation of experience, and you can write more slowly. Look more at some of the better structures written by others, copy them first, and then slowly change them to gradually make them what you want.

Write at the end

I especially like the quote at the beginning of the book: "Make the camp cleaner than when you came!"

If every time you check in, the code is cleaner than when you check out, then the code will not be corrupted. It does not necessarily take much effort to clean up, maybe just change a variable name, split a function that is a bit too long, eliminate a little bit of duplicate code, and clean up a nested if statement.

Every member, every time the code is moved in, can do this, so the code will not rot.

Finally, I recommend everyone to read the book "Code Cleanliness"~

Guess you like

Origin blog.csdn.net/lizebin_bin/article/details/103941261