头图

🤫 Whisper reminder 🤫

Follow Zilliz WeChat public account and reply to "clean code"

Get the super detailed mind map of "The Way to Clean Code"

图片

Why should we pursue clean code?

"Clean Code" (Clean Code) proposed that the code is directly proportional to its cleanliness.

Just letting the code run is not enough, because the demand continues to grow, and the code needs to keep pace with the times: adding new features, modifying existing functions, optimizing performance... Large-scale projects require a team to maintain the code together.

In team collaboration, redundant logic and messy code will waste a lot of time and resources. After all, no one wants to hold a nose to maintain a "💩💩⛰️". Therefore, excellent software engineers pursue the "cleanliness" of the code, and it is their responsibility to write code that is pleasing to the eye, extensible, and easy to maintain.

图片

The book "The Clean Code" is exactly the 16182338268f5a 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 younger programmers. In 2001, he and 16 other top software industry leaders jointly signed the "Agile Development Manifesto", which established core values for efficient and collaborative software development processes, and "Code Cleanliness" helped lay the foundation for agile development. Provides a set of effective operating instructions.

Whether you are a developer, software engineer, project manager, or team leader, if you want to stay professional and keep improving, you should read this book.

You will get from this book:

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

What does neat code look like?

In the first chapter, the author quoted the words of Bjarne Stroustrup, the inventor of the C++ language:

Code logic should be straightforward, making defects difficult to hide; minimize dependencies to make it easy to maintain; improve error handling code according to a certain layering strategy; optimize performance to save trouble for others to make unruly optimizations and make a bunch Chaos comes. Clean code only does one thing well.

In addition, clean code should also:

  • Easy to read and can be supplemented by developers other than the author
  • There are unit tests and acceptance tests
  • Use meaningful names
  • Keep dependencies as simple as possible
  • The code should express its meaning literally
  • No duplicate code

How to "clean up" your code?

The author takes the detours he has traveled as an example and gives a large number of cases of "cleaning up the code". Through specific cases, the author leads readers to turn the problematic 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 code below?

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 logos, etc., which is a headache. Just do a few simple methods of extracting and renaming operations, 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 puts some settings and disassembly pages into a test page, and then renders it as HTML.

But this optimization is not neat enough, the author said, "The first rule of functions is to be shorter. 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 all written in the Java language, and some of the cases are specifically for Java. If you use other languages, you can move on and understand the core ideas in the book.

The editor found a project on GitHub that uses JavaScript to interpret the concept of "Clean Code". The project gives a large number of good and bad examples with comments as an explanation to help readers understand the concept of "Clean Code"👇👇 👇

图片

Clean Code Javascript code address: https://github.com/ryanmcdermott/clean-code-javascript

Smell and inspiration

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

Take writing notes as an example, "bad smell" includes:

  • Redundant notes
  • The code that is commented out (the code should be deleted in time)
  • ……

For naming, examples of "good smell" include:

  • Use a descriptive name
  • The name is unambiguous
  • Use standard naming methods
  • Explain side effects
  • ……

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

Want to know more details? Follow the Zilliz WeChat public account and reply to the title of the book "clean code" , you can get the "Clean Code" high-definition mind map compiled by the editor.

Welfare time

How do you improve your code level?

What bad code habits do you most want to complain about?

If you are interested in technology, what good books do you have?

Welcome to leave a message in the WeChat comment section of your thoughts ,

We will choose a small partner,

presented a paper version of "The Way to Clean Code"!

It is important to accumulate the amount of code,
Reading and reading good books are also very important.
"Zilliz Book Recommendation" column,
Aim to share books about technological growth with you,
Read the book thick with you first, and then read the book thin.

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. The Milvus database is a graduate project of the LF AI & Data Foundation. It can manage a large number of unstructured data sets and has a wide range of applications in new drug discovery, recommendation systems, and chatbots.


Zilliz
154 声望829 粉丝

Vector database for Enterprise-grade AI