Abstract:

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Average engineers pile code, good engineers elegant code, great engineers simplify code. How to write elegant, clean and easy to understand code is a science and an important part of software engineering practice. The author recommends three classic books code neat way, the art of readable code, refactoring: improving the design of existing code, the focus will be from below comments, naming, method, abnormal, unit testing, and other aspects summarizes some code neat and best practices, mostly the author summarizes the essence in the above three books, There are also some summaries of the author’s engineering practice. As space is limited, this article will summarize some practical suggestions, and a follow-up article will give some examples of code neatness.

annotation

  • Don’t comment on a bad name. A good name is more important than a good comment
  • Don’t “crutch comment”, good code > bad code + good comment
  • Use global annotations at the file/class level to explain how all parts work
  • Be sure to comment out constants
  • The team defines the markup uniformly

    • TODO pending issues
    • FIXME knows about the problematic code
    • The crude solution HACK had to adopt
  • Use carefully selected input and output examples in the comments
  • Comments should state the high-level intent of the code, not the obvious details
  • Don’t add code authoring information to your code, and don’t delegate what Git can do to your code
  • HTML comments in source code are a nuisance that makes reading difficult
  • Comments must describe the code closest to them
  • Comments must correspond to the code
  • The public API needs to be annotated, and the rest of the code uses annotations carefully
  • Typical bad comment

    • Inappropriate information
    • Deprecated comment
    • Redundant annotation
    • Bad comment
    • Comment out code
  • The only really good comments are the ones you try not to write

    • Don’t have regular comments, such as setter/getter comments
    • Don’t add logging comments, such as changing the time (something Git can do)
    • Comments must express something other than code, something that code can contain, and must not appear in comments
    • If you need to comment, comment the intent (why), not the implementation (how). Everyone will look at the code
    • Add warning comments as appropriate

named

  • Use standard naming methods whenever possible, such as design patterns, generic academic terms, etc
  • Look for more expressive words

    • Use more technical words, such as fetch or download instead of get
    • Avoid generic names like TMP
    • Use specific names to describe things in detail
    • Add important details to variable names, such as the unit ms
    • Use longer names for larger names and shorter names for smaller ones
    • If the variable type is Boolean, it will be made more explicit by adding is, has, can, should, etc
  • The length of a variable name should correspond to its scope
  • Don’t be afraid of long names. Long, descriptive names are better than short, confusing ones
  • The function name should say anything about the side effect. The name should say everything about the function, variable, or class. Please do not hide the side effect, such as CreateAndReturnXXX

methods

  • Functions should not be 100 lines long, 20 lines is best

    • Control statements such as if else while should have a single line of code block, i.e. a function call statement
    • Functions should be locked at no more than two levels
    • A function only does one thing, and a function should not be able to abstract out another function
  • A private function called by a public function follows
  • The ideal parameter is zero, with no more than three input parameters and no output parameters

    • If a function takes three or more arguments, it is best to abstract it as a class
    • Identification parameters are ugly, passing booleans to functions to distinguish between different businesses is ugly, and should be split into multiple functions
  • Do not return null values, throw exceptions, or return special objects. Avoid NPE
  • Do not pass in null values

Exceptions and errors

  • Extract a block of code contained in a try catch that is abstracted as a function
  • Each exception thrown should provide sufficient context to determine the source and location of the error
  • Don’t blame system errors on happenings

concurrent

  • Separate concurrent code from other code
  • Strictly restrict access to data that may be shared
  • Avoid using multiple synchronization methods for a shared object
  • Keep the synchronization area small and design as few critical sections as possible

Unit testing

  • Don’t be afraid that the method names of your unit tests are too long or cumbersome; test function names are like comments
  • Don’t aim for high test coverage; the first 90% of your code usually takes less time to test than the last 10%
  • Use the simplest test input that can work through the entire code
  • Give the Test function a descriptive name with integrity, such as Test _
  • Testing code is just as important as production code
  • If the test code is not clean, you will lose it quickly
  • One assertion per test, and the number of assertions in a single test should be minimized to one assertion
  • The FIRST principle

    • Fast Fast
    • Independent tests should be Independent of each other
    • Repeatable tests should be passed repeatedly in any environment
    • Self-sufficient validation -Validating tests should have Boolean output
    • The best way to Timely is TDD

The code structure

  • Code line length is limited to 100-120 characters
  • It is possible to build excellent systems out of single files, most of which are 200 lines long and up to 500 lines long
  • Closely related code should be close to each other

    • Variable declarations should be close to where they are used
    • If one function calls another, they should be placed together, and the caller should be placed on top of the called
    • Shows the order of function call dependencies from top to bottom
  • The function that explains the intent of the condition should be isolated and expressed as positively as possible
  • Do not inherit constants, such as defining constants in interfaces, and do not use inheritance to cheat the scope rules of a programming language
  • A module should not know the internals of the objects it operates on
  • DTO (Data Transfer Objects) is a class with only public variables and no functions
  • Object exposes behavior and hides data
  • Do not use “Yoda notation” such as if(null == obj), modern compilers warn against code such as if(obj = null)
  • The general case uses if else, and simple statements use the trinary operator
  • In general, returning early reduces nesting and keeps code clean

design

  • Classes should be short enough

    • Classes should satisfy the single responsibility principle (SRP); classes and modules have only one reason to modify
    • Classes should have only a few entity variables
    • Classes should follow the Dependency Inversion Principle (DIP). Classes should depend on abstractions rather than details
    • The fewer methods in a class the better, the fewer variables a function knows, and the fewer entity variables a class has, the better
  • Make your code more readable by reducing the number of variables and making them as “lightweight” as possible

    • Reducing the variable
    • Reduce the scope of a variable
    • It is better to write variables only once, such as constants
  • The best code to read is no code

    • Eliminate unnecessary features from the project and don’t over design
    • Rethink the requirements and solve the simplest problems of the release, as long as it gets the job done
    • Read through the library’s entire apis regularly to keep up with them
  • Simple design

    • Run all tests
    • Do not repeat
    • Expresses the intent of the programmer
    • Minimize the number of classes and methods
    • The above rules are listed in order of importance
  • Whether designing systems or individual modules, don’t forget to use the simplest solution that probably works
  • Clean code provides one way to do one thing, not many, with as few dependencies as possible. Define and provide as few apis as possible
  • Reduce repetitive code, improve expression, build early, simple and abstract

summary

This article, the first in a series of clean Code practices, briefly Outlines some best practices from the perspectives of comments, naming, methods, unit testing, concurrency, and more, and we’ll cover more practice examples from each area in the following sections. I believe that every good engineer has a heart to pursue excellent code, what are your good suggestions on code clean engineering practice? How do hundreds of people collaborate to make code clean and consistent? Welcome to the discussion.

Author:
Bamboo jian

The original link

This article is the original content of the cloud habitat community, shall not be reproduced without permission.