Writing code is like writing articles. Clean code is comfortable to read and easy to maintain later.

I recently read a book called “The Way To Clean Code.” The author summed up a number of practical practices for writing clean code, which have high reference value.

“There are two reasons to read this book: first, you’re a programmer; Second, you want to be a better programmer.”

How do you measure code quality? An easy way to do this is to look at how many times you say “WTF” per minute while reading code. The more times you say “WTF”, the lower your code quality.


Why care about code cleanliness? Because code quality is positively related to its cleanliness. Unlike programmers who believe in “just run,” good programmers make their code run while also making it beautiful. Bjarne Stroustrup, author of C++Programming Language, is a good example. “I like elegant and efficient code,” he says. The code logic should be so straightforward that defects are hard to hide; Minimize dependencies and make them easy to maintain; Refine error-handling code according to a hierarchical strategy; Optimize performance to avoid tempting others to do unruly optimization and create a mess. Clean code does one thing.”

To write clean code, practice. Make it a habit to read a lot of code over and over again, and to think about what’s good or bad about a particular piece of code. Code neatness should start with all aspects of the program, including formatting, naming, comments, classes, error handling, and so on.

Named after 0.

First, variable names should make sense, and people should know (guess) “what is this” as soon as they see a variable. Bad variable names are the first barrier to getting someone to read your code. Take the following example.

public List<int[]> getThem() {

  List<int[]> list1 = new ArrayList<int[] > ();

  for (int[] x : theList)

  if (x[0] = =4)

  list1.add(x);

  return list1;

}

Copy the code

When you see code like this, your first instinct might be to wonder about the variable names in the code.

(1) What kind of things are in theList? (2) What is the significance of theList sub-zero scale entry? (3) What is the significance of the value of 4? (4) How do I use the returned list?

A slight improvement in the naming would make the readability much better.

public List<int[]> getFlaggedCells() {

  List<int[]> flaggedCells = new ArrayList<int[] > ();

  for (int[] cell : gameBoard)



  if (cell[STATUS_VALUE] == FLAGGED)

  flaggedCells.add(cell);

  return flaggedCells;

}

Copy the code

Second, don’t give misleading names. “A really scary example of misleading names is the use of lowercase L and uppercase O as variable names, especially when combined.”

int a = l;

if (O == l)

  a = O1;

else

  l = 01;

Copy the code

Use pronounceable names to make the discussion easier.

/ /

class DtaRcrd102 {

    private Date genymdhms;

    private Date modymdhms;

    private final String pszqint = "102";

    / *... * /

};



/ / is

class Customer {

  private Date generationTimestamp;

  private Date modificationTimestamp;;

  private final String recordId = "102";

  / *... * /

};

Copy the code

Class 1.

“Class and object names should be nouns or noun phrases, such as Customer, WikiPage, Account, and AddressParser. Avoid class names like Manager, Processor, Data, or Info. Class names should not be verbs. The method name should be a verb or phrasal verb such as postPayment, deletePage, or save.”

“The name of the class should describe its rights and responsibilities. In fact, naming is the first tool to help determine the length of a class. If you can’t give a class an exact name, the class is probably too long. The more ambiguous the class name, the more likely it is to have too many rights and responsibilities. For example, if the class name includes an ambiguous word, such as Processor or Manager or Super, this is often indicative of an inappropriate aggregation of responsibilities.”

“Classes should only have a few entity variables. Each method in a class should operate on one or more of these variables. In general, the more variables a method operates on, the more it sticks to the class. A class has maximum cohesion if every variable in it is used by every method.”

2. The function

  • “The first rule of functions is to be short. Rule number two is shorter.”

  • “The function should do one thing. Do it well. Do only one thing.”

In general, functions, as an encapsulation of a logical process, should do as little as possible. Also pay attention to the order in which the code is read. We read the code from top to bottom, so each function should be followed by a function at the next level of abstraction, so that when viewing the list of functions, we can sequencing down the abstraction level. This is called the downward rule.

Function parameters are also worth paying attention to.

“The optimal number of arguments is zero (zero-argument function), followed by one (single-argument function), then two (two-argument function), and three (three-argument function) should be avoided as much as possible.” If a function has more than three arguments, it should be passed in a wrapper, such as a C structure, an OOP class, and so on.

For functions with more than one parameter, make it easier to distinguish the parameters. Do not design parameters with similar meanings, which can easily confuse the caller. “Even binary functions such as assertEquals(Expected, actual) have their problems. How often do you misplace “actual” and “expected”? There is no natural order for these two parameters. Expected before, actual after, just a convention to be learned.”

3. Comments

Many would argue that writing comments makes your code more readable. This is not necessarily the case.

“The proper use of comments is to compensate for our failure to express intent in code. Notice that I used the word “failure”. I mean it. Comments are always a failure. We can’t find a way to express ourselves without annotations, so there are always annotations, and that’s not something to celebrate.”

“There’s nothing more useful than well-placed comments. Nothing messes up a module like messy comments. There’s nothing more damaging than old, misinformed comments.”

“Inaccurate annotations are much worse than no annotations at all. They’re full of shit. What they anticipate never materializes. They set old rules that need not and should no longer be followed. There is only one place for truth: code. Only code can faithfully tell you what it does. That’s the only really accurate source of information. So, while annotations are sometimes needed, we should also make an effort to keep them to a minimum.”

“Clean, expressive code with a few comments is much more presentable than fragmented, complex code with a lot of comments. Instead of spending time writing comments that explain the bad code you’ve created, spend time cleaning up the bad code.”

“TODO is something that programmers think they should do, but for some reason aren’t doing yet. It might be a reminder to remove an unnecessary feature, or to call attention to a problem. It might be a plea for a good name, or a reminder of changes that depend on a scheduled event. Whatever TODO’s purpose, it’s not an excuse to leave bad code in the system.”

“Adding comments just because you feel you should or because the process requires it is pointless. If you do decide to write a comment, take the time necessary to make sure you write the best comment.”

“The rule that every function should have Javadoc or every variable should have comments is just plain silly. These types of comments make the code messy, gibberish, and confusing.”

“Sometimes programmers like to mark a particular location in the source code. For example, I recently saw this line in the program:

// Actions //////////////////////////////////

Copy the code

Most of the time it is unreasonable to place a particular function under such a bar. It’s rubbish and should be deleted — especially that long, useless slash at the end.”

“It’s annoying to comment out code. Don’t do that! Others are afraid to delete commented out code. They think there must be a reason the code is still there, and it’s too important to delete. The commented out code piles up like the dregs at the bottom of a broken bottle.”

“HTML tags in source code comments are a nuisance. Code in an editor or IDE that is easy to read becomes difficult to read because of HTML comments. If the comments are going to be extracted by a tool (such as Javadoc) and rendered to a web page, it is the tool’s responsibility, not the programmer’s, to tag the comments with the appropriate HTML.”

4. The format

The layout of your code is also important. Today’s editors have the ability to format code, which can quickly add to the overall aesthetic of your code.

For loop statements, if the body of the loop has only one statement or is empty, many people may omit the braces. Try not to do that.

“Sometimes the body of a while or for statement is empty. I don’t like this structure and try not to use it. If it is unavoidable, make sure the empty range body is indented, surrounded by parentheses. I can’t tell you how many times I’ve been fooled by a semicolon sitting quietly at the end of the same line as a while loop. It’s hard to see that semicolon unless you put it on another line and indent it.”

while (dis.read(buf, 0, readBufferSize) ! = -1)

;

Copy the code

5. Error handling

“I think in order to talk about error handling, you have to talk about error prone practices. The first is to return null. I don’t want to count how many applications I’ve seen where almost every line of code checks for null.”

“By returning null, you’re basically creating more work for yourself and for the caller. If null is not checked at any point, the application loses control.”

“Returning null values in a method is bad practice, but passing null values to other methods is even worse. Unless the API requires you to pass null to it, avoid passing null whenever possible.”

Unit testing

“Everyone knows that TDD requires us to write unit tests before we write production code. But this rule is just the tip of the iceberg. Take a look at these three laws: Law no. 1 Do not write production code until you write unit tests that fail. Rule two only allows you to write unit tests that just fail, and fail to compile. Rule three only writes production code that is just enough to pass the current failing test.”

“Tests are written with production code, and tests are written only a few seconds before production code.”

Step 7 Improve

No one can write neat, beautiful code the first time. Writing clean code is a process of gradual improvement.

“To write clean code, you must first write dirty code and then clean it up.”

“Most novice programmers (like most elementary school students) don’t follow this advice particularly carefully. The first task, they believe, is to write programs that work. As long as the program “works,” it moves on to the next task, leaving the “working” program in its last “working” state. Most experienced programmers know that this is self-destructive.”

Note: Some of the views, code and images in this article are from the original book. The copyright is Robert C. Martin.