(welfare at the end of the article) what is the ultimate standard to measure the quality of code?

Keywords: Java Javascript Code Style

🤫 Whisper reminder 🤫

Pay attention to Zilliz WeChat official account and reply to "clean code"

Get the super detailed mind map of code neatness

Why should we pursue clean code?

Clean Code puts forward that the quality of code is directly proportional to its cleanliness.

Just let the code run is not enough, because the demand is growing, and the code needs to keep pace with the times: add new features, modify existing functions, and optimize performance... For projects with large quantities, the team needs to jointly maintain the code.

In team collaboration, redundant logic and chaotic code will waste a lot of time and resources. After all, no one wants to hold his nose to maintain a " 💩💩⛰️」. Therefore, excellent software engineers pursue the "cleanliness" of code and take it as their responsibility to write pleasing, scalable and easy to maintain code.

The book "the way to clean code" is a code cleaning guide. The author of this book is Robert Martin, a leader in the software industry. He is a pioneer in design patterns and agile development. He is respected as "Uncle Bob" by future programmers. In 2001, he signed the agile development declaration with 16 other top software industry leaders , it establishes core values for an efficient and collaborative software development process, and the way to clean code helps lay the foundation for agile development and provides a set of effective operation guidelines.

Whether you are a developer, software engineer, project manager or team leader, you should read this book if you want to remain professional and constantly improve.

You will get from this book:

  • Learn how to distinguish between good and bad codes and quickly identify "dirty" codes
  • Learn to optimize the code and make the code correct, concise, beautiful and sustainable
  • Make the code easy to read and understand, and help your teammates save time
  • Develop the habit of using automated testing and unit testing to avoid a vicious circle
  • Understand true professionalism

What does clean code look like?

In Chapter 1, the author quotes Bjarne Stroustrup, the inventor of C + + Language:

Code logic should be straightforward, so that defects are difficult to hide; reduce dependencies as much as possible to make it easy to maintain; improve error handling code according to a hierarchical strategy; optimize performance to avoid bothering others to do irregular optimization and create a pile of confusion. Clean code can only do one thing.

In addition, clean code should:

  • It is easy to read and can be added by developers other than the author
  • There are unit tests and acceptance tests
  • Use meaningful naming
  • Keep dependencies as simple as possible
  • The code shall express its meaning literally
  • No duplicate code

How to "clean up" your code?

Taking his detours as an example, the author gives a large number of "code cleaning" cases. Through specific cases, the author leads the readers to turn the problem code base into a robust and efficient code base.

Let's take a minute or two to look at a case. How much can you understand the following code?

Code listing 3-1 HtmlUtil.java (bad example)

public static String testableHtml(
  PageData pageData,
  boolean includeSuiteSetup
) throws Exception {
  WikiPage wikiPage = pageData.getWikiPage();
  StringBuffer buffer = new StringBuffer();
  if (pageData.hasAttribute("Test")) {
    if (includeSuiteSetup) {
      WikiPage suiteSetup =
      PageCrawlerImpl.getInheritedPage(
              SuiteResponder.SUITE_SETUP_NAME, wikiPage
      );
      if (suiteSetup != null) {
      WikiPagePath pagePath =
        suiteSetup.getPageCrawler().getFullPath(suiteSetup);
      String pagePathName = PathParser.render(pagePath);
      buffer.append("!include -setup .")
            .append(pagePathName)
            .append("\n");
      }
    }
    WikiPage setup =
      PageCrawlerImpl.getInheritedPage("SetUp", wikiPage);
    if (setup != null) {
      WikiPagePath setupPath =
        wikiPage.getPageCrawler().getFullPath(setup);
      String setupPathName = PathParser.render(setupPath);
      buffer.append("!include -setup .")
            .append(setupPathName)
            .append("\n");
    }
  }
  buffer.append(pageData.getContent());
  if (pageData.hasAttribute("Test")) {
    WikiPage teardown =
      PageCrawlerImpl.getInheritedPage("TearDown", wikiPage);
    if (teardown != null) {
      WikiPagePath tearDownPath =
        wikiPage.getPageCrawler().getFullPath(teardown);
      String tearDownPathName = PathParser.render(tearDownPath);
      buffer.append("\n")
            .append("!include -teardown .")
            .append(tearDownPathName)
            .append("\n");
    }
    if (includeSuiteSetup) {
      WikiPage suiteTeardown =
        PageCrawlerImpl.getInheritedPage(
                SuiteResponder.SUITE_TEARDOWN_NAME,
                wikiPage
        );
      if (suiteTeardown != null) {
        WikiPagePath pagePath =
          suiteTeardown.getPageCrawler().getFullPath (suiteTeardown);
        String pagePathName = PathParser.render(pagePath);
        buffer.append("!include -teardown .")
              .append(pagePathName)
              .append("\n");
      }
    }
  }
  pageData.setContent(buffer.toString());
  return pageData.getHtml();
}

In the above code, there are too many different levels of abstraction, strange strings, function calls, mixed with double nesting, if statements controlled by identification, etc. It's a headache. Just do a few simple methods to pull out and rename, plus a little refactoring, and you can do it in the next few lines of code:

Code listing 3-2 HtmlUtil.java (after refactoring)

public static String renderPageWithSetupsAndTeardowns(
  PageData pageData, boolean isSuite
) throws Exception {
  boolean isTestPage = pageData.hasAttribute("Test");
  if (isTestPage) {
    WikiPage testPage = pageData.getWikiPage();
    StringBuffer newPageContent = new StringBuffer();
    includeSetupPages(testPage, newPageContent, isSuite);
    newPageContent.append(pageData.getContent());
    includeTeardownPages(testPage, newPageContent, isSuite);
    pageData.setContent(newPageContent.toString());
  }

  return pageData.getHtml();
}

This code is much clearer than the first example. You can probably understand that this function needs to put some setup and disassembly pages into a test page and render them as HTML.

But this optimization is not neat enough. The author said, "the first rule of function is to be short. The second rule is to be shorter."

After refactoring again, the code is finally clear at a glance:

Code listing 3-3 HtmlUtil.java (after refactoring again)

public static String renderPageWithSetupsAndTeardowns(
  PageData pageData, boolean isSuite
) throws Exception {
  if (isTestPage(pageData))
    includeSetupAndTeardownPages(pageData, isSuite);
  return pageData.getHtml();
}

It should be noted that the cases in the way to clean code are written in Java language, and some cases are specifically aimed at Java. If you use other languages, you can transfer flowers and trees and understand the core ideas in the book.

Xiaobian found a project on GitHub that uses JavaScript to interpret the concept of "Clean Code". The project gives a large number of examples of good / bad, supplemented by notes to help readers understand the concept of "Clean Code" 👇👇👇

Clean Code Javascript code address: https://github.com/ryanmcderm...

Smell and inspiration

How to "smell the code"? The author summarizes some "bad smell" and "good smell". Bad smell refers to some omissions and small errors in the code. Developers can track down bigger problems in the code through these detailed signs; good smell refers to some rules that should be followed.

Taking notes as an example, "bad smell" includes:

  • Redundant notes
  • Commented out codes (these codes should be deleted in time)
  • ......

For naming, examples of "good smell" include:

  • Use descriptive names
  • The name is unambiguous
  • Use standard naming methods
  • Explain the side effects
  • ......

This list is difficult to exhaust all the rules. The value system behind the list is the goal of "code cleanliness".

For more details? Zilliz clean official account and reply to the title "clean code", you can get the high-definition mind map of the code tidiness.

Welfare time

How did you improve your code?

What bad habits do you want to make complaints about?

Interested in technology, what good books do you have in mind?

Welcome to leave your thoughts in the wechat comment area

We will choose a little partner,

Give away a paper version of the way to code neatness!

It's important to accumulate code,
Reading and reading good books are also very important.
"Zilliz good book recommendation" column,
Books designed to share technology growth with you,
Read the book thick first and then thin with you.

With the vision of redefining data science, Zilliz is committed to building a world leading open source technology innovation company, and unlocking the hidden value of unstructured data for enterprises through open source and cloud native solutions.

Zilliz built the Milvus vector database to accelerate the development of the next generation data platform. Milvus database is a graduation project of LF AI & data foundation. It can manage a large number of unstructured data sets and is widely used in new drug discovery, recommendation system, chat robot and so on.

Posted by kaushikgotecha on Wed, 03 Nov 2021 00:13:13 -0700