sequence

1. Lebron’s Law — Later equals no

2. You shouldn’t be shy about telling people what you think

We may blame our messy code on a product-manager focused on the project schedule, or on demanding users, but we are simply being unprofessional. Unreasonable requests should be addressed. Most managers want to know the truth, even if they don’t seem to like it. Most managers want good code, even if they’re obsessed with progress. They will defend progress and demand vigorously, as they should. So we should guard code with the same passion.

One, meaningful naming

3. Keep code blocks as small as possible

In fact, people have been saying this for as long as there has been software. the smaller the better

4, name as much as possible

  • The name of a variable, function, or class should answer all the big questions.
  • Don’t be afraid of long names.
  • Choosing a good name takes time, but it saves more time than it takes.
  • Replace the old one as soon as a better one becomes available.

5, naming to avoid misleading

  • Avoid using words that are contrary to their original meaning.
  • Do not refer to a group of accounts as accountList unless it is really a List. The word List has special meaning for programmers. If the package account container is not really a List, unless it is really a List. Even if the container is a List, it is best not to write the container name in the name. It’s even better to use accounts directly. (PHP doesn’t have these requirements.)
  • Don’t use similar names

Nonsense is redundancy

Try to avoid nonsense in naming.

7, naming to use as far as possible to read the name

Humans are good at remembering and using words.

8. Define constants !!!!

Easy to find and modify.

9. Avoid mental mapping

Loop counters are naturally likely to be named I or J or K (but don’t use the letter I) because of the traditional conventional but alphabetic names for loop counters. Otherwise it’s best not to use it.

10. The class name should be a noun, like Customer, not a verb.

Method names should be verbs or phrasal verbs.

12. Each concept corresponds to a word

Controller or something like that

Second, the function

13, short

  • The first rule of functions is to be short
  • The second rule of functions is even shorter

Only do one thing

The function should do one thing. Do it well. Do only one thing. One way to tell if Korean is doing more than one thing is to see if you can split out another function. Changing a function is more than just reinterpreting its implementation.

15. One level of abstraction per function

What is a level of abstraction? String pagePathName = pathParser.render (pagePath) is the intermediate abstraction layer. Append (“\n”) is the low abstraction layer

16, Switch statement

  • Make sure that each switch is buried at a lower level of abstraction and never repeats
  • The single accountability principle simply means that one class is responsible for one responsibility.
  • Software entities (classes, modules, functions, and so on) should be extensible but not modifiable.
  • As abstract as possible The sample
public Money calculatePay(Employee e)
throws InvalidEmployeeType {
   switch (e.type) {
        case COMMISSIONED:
            return calculateCommissionedPay(e);
        case HOURLY:
            return calculateHourlyPay(e);
        case SALARIEED:
            returncalculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); }}Copy the code

The above code may have similarly structured functions everywhere. It may be isPayday(Employee E, Date Date) or deliverPay(Employee E, Date Date);

The solution: ** bury the switch statement underground in the abstract factory, where no one can see it. The factory uses the Switch statement to create the appropriate entities for the Employee pie, while different functions, such as calculatePay, isPayday, and deliverPay, accept dispatals through the Polymorphic Employee interface.

17. Function parameters

  • The optimal number of parameters is zero (zero-parameter function), followed by one (single-parameter function), and then two (two-parameter function). Three (three-parameter function) should be avoided as much as possible. There is a sufficiently special reason to use more than three arguments (multi-argument functions). — So don’t do it anyway. If a function looks like it needs two, three, or more arguments, some of them should be wrapped as classes.

18, no side effects

What are side effects? The side effect is that functions promise to do one thing, but still do other hidden truths. If we ignore it, we may be doing something we don’t expect.

19. Output parameters

static void appendFooter(StringBuilder sb) {
        sb.append("Here you go!");
    }
Copy the code

We should try to avoid using appendFooter(s). The report.appendfooter () method should be used whenever possible. Because we would waste time checking function declarations. Most of the need for output parameters in object-oriented languages has gone away, because this also means output function.

20. Use exceptions instead of returning error codes

Cause: Deep nested structures require immediate handling of errors when an error code is returned. With exceptions, the error-handling code can be separated from the main path code and simplified.

21. Remove the Try/Catch block

The Try/Catch block is ugly. They mess up the code structure and confuse bad code handling with normal flow. It is best to separate the body of the try and catch blocks and form separate functions.

Error handling is one thing

The function should only do one thing. Error handling is one thing.

Error. Java relies on magnets

Returning error codes usually implies that there is a class or enumeration somewhere that defines all error codes. If you use it, all these other classes need to be recompiled and deployed when the Error enumeration changes. This puts negative pressure on the Error class, so programmers use the old Error code and are reluctant to add new Error code. Using exceptions instead of error codes, new exceptions can be derived from the exception class. No recompilation or redeployment is required.

24, don’t repeat yourself!! !

Don’t write repetitive code. Repetitive code increases the chance that errors will be ignored

Three, comments,

The comments show that our code is not good. But sometimes we have to write comments. But programmers don’t maintain comments in a timely manner, so over time comments get further and further away from the code they describe. The only really good comments are the ones you try not to write and replace the urge to create crap with the determination to clean up the code.

25, warning notes

26. TODO notes

27. Comments after parentheses

//while //try similar this makes sense for deep nesting but why not write smaller, encapsulated functions?

28. Commented out code

It’s annoying to comment out code. Don’t do that!! The possible reason is: 1 ️ dare not remove 2 discount ️ used to prompt 3 discount…… But all of this admittedly messed up the code and now the source control system has made sure that the code can’t be lost, just delete it

Four, format

To be clear, code formatting is important, and it must be taken seriously. (Before me …………)

29. Vertical partitions between concepts

Between package declarations, import declarations, each function, and so on. Separated by a blank line. This extremely simple rule is great for code reading.

30. Vertical proximity

Closely related code should be close together to make it easier to read and understand.

31. Vertical distance

  • Closely related concepts should be close to each other to help understand what the system does. Instead of putting time and effort into finding and remembering where the code fragments are. (Unless there’s a good reason to keep it in a different file)
  • Variable declarations should be made as close as possible to where they are used.
  • Entity variables Entity variables should be declared at the top of the class.
  • Related functions If one function calls another, they should be placed together, and the caller should address the caller as far as possible.
  • Concept-related code should be grouped together. The stronger the correlation, the shorter the distance.

32. Horizontal format

Keep lines of code as short as possible. There’s a rule to follow: don’t drag the scroll bar to the right.

Objects and data structures

Object exposes behavior and hides data. Easy to add new object types without modifying existing behavior. It is also difficult to add new behaviors to existing objects. Data structures expose data without obvious behavior, making it easy to add new behavior to existing data structures and difficult to add new data structures to existing functions.

Error handling

Error handling is important, but if it messes up the code logic, it’s the wrong thing to do

33. Use exceptions instead of return codes

If an error code is used, the caller must check for the error immediately after the call. Unfortunately, this step is easy to forget.

34. Write a try-catch-finally statement first

One of the nice things about exceptions is that when they define a scope ina program to execute the try part of a try-catch-finally statement, they are indicating that execution can be cancelled at any time and continue in the catch statement. Before writing code that might throw an exception, it is best to write the try-catch-finally statement first. This helps you define what users of your code should expect. It doesn’t matter what happens to the code that executes in the try block, right

35. Use uncontrollable exceptions

  • The price of controlled exceptions is a violation of the open/close principle.
  • If you throw a controlled exception in a method and the catch statement is three levels above it, you have to declare that exception in every method signature between the catch statement and where the exception was thrown.
  • And so on, the end result is a chain of changes that runs from the bottom of the software to the top.
  • It’s a shame that managed exceptions break encapsulation in this way
  • For general application development, the dependency costs of controllable exceptions are higher than the benefits.

36. Give the description of the abnormal environment

Helps identify the source and location of the error.

Call the exception class according to the caller’s needs.

For example:

ACMEPort port = new ACMEPort(12);

try {
    port.open();
 } catch (DeviceReesponseeException e) {
    reportPortError(e);
    logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
    reportPortError(e);
    logger.log("Unlock exception", e);
} catch (GMXError e) {
    reportPortError(e);
    logger.log("Device response exception");
} finally {
...
}
Copy the code

The above statement contains a lot of duplicate code. We can package the new port and exception handling into a new function.

It’s a good idea to package third-party apis. When you package a third-party API, you reduce your dependence on it: you can switch to another code base in the future without too much pain. Packaging also helps simulate third-party calls when you test your own code.

38, Do not return null

39, Do not use null values

Unit testing

The three Laws of TDD

TDD, short for Test-driven Development (TEST-Driven Development), is a core practice and technology in agile Development, as well as a design methodology. TDD works by writing unit test case code before developing functional code, which determines what product code needs to be written. TDD, while a core practice of Agile methods, applies not only to XP (Extreme Programming) but also to other development methods and processes.

  • Rule 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 allows you to write only production code that is just enough to pass the current failing test.