Shaping high-quality code

The three elements of good code

  • readability
  • maintainability
  • alterability

Clean code features

  • Good naming
  • Good code style
  • Good software design

Let’s start by recognizing that clean code is closely related to high-quality code. In other words, to write high-quality code, code needs to be clean and readable. Here are some basic principles and specifications for writing code.

named

“There are two hard things in computer science: cache invalidation and naming.” (There are only two hard things in ComputerScience: Cache Invalidation and Naming things.) — Martin Fowler

Meaningful naming

Code is documentation, and readable code should be self-explanatory, meaning that the code itself explicitly expresses the developer’s intent without the help of comments and documentation

  1. Variable names, constant names — nouns or noun phrases, such as variable namesdThere is noremainingTimeInDayNaming concrete, more meaningful.
  2. Function name, method name – verb or phrasal verb, (usually the first word is verb), and specific names. Vague names don’t make sense. (processData()A function should be named for what it does, not how it does it. For example:validateUserCredentials().
  3. Class name — noun or noun phrase

Naming consistency

  1. Use antithesis words, as in the following example.
  2. Post-determiners (e.g. Total, Sum, Average, Max, Min……)
  3. Unified Business Language (Using namespaces)

Examples of antithesis words

first/last
min/max
add/remove
increment/decrement
open/close
begin/end
insert/delete
show/hide
create/destroy
lock/unlock
source/target
Copy the code

Recommended naming tools

CODELF salad look up words

specification

Naming conventions

Common naming methods include: Big hump — PascalCase Small hump — camelCase All lowercase, kebab-case all uppercase, underscore _ (CONST_CASE) all lowercase, underscore _ (lower_case)

Annotation specifications

Good comment

  1. Provides the intent and purpose behind the code to help explain the meaning of the code
  2. A comment used to warn other programmers of a consequence
  3. TODO comments, work that hasn’t been done yet for some reason

Bad comments

  1. Do not have outdated notes, which will mislead posterity
  2. You don’t need to comment code that is literal.

Specification added

  1. Use intermediate variables wisely to increase readability
  2. Use design pattern languages such as vUE’s Observer pattern and publish subscribe pattern Observer, subscribe
  3. A simple rule of thumb is to put conceptually related code together: the stronger the correlation, the shorter the distance from each other. Blank lines are used correctly to increase code readability.
  4. Use constants instead of magic numbers
  5. Preventing the broken Window effect — a famous theory in criminal psychology. Don’t be the first to write “bad taste” code

Use intermediate variables wisely

Use blank lines correctly to increase code readability

Use Constants correctly

function

The first rule is to be smaller, the second rule is to be smaller. The function should do one thing. Do it well. Do only one thing, the single responsibility principle at the function level.

Function parameters

  1. 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. There is a sufficiently special reason to use more than three parameters (multi-parameter function)
  2. If the function appears to need two, three, or more arguments, you can use objects instead

The principle of function

Everyone has an obligation to defend, abide by or perfect principles. Principles can be amended, but not arbitrarily. Principles are a guide to writing better code and understanding the ideas behind it.

The principle of SOLID

  • Single Responsibility Principle (SRP) :
  • Open Close Principle (OCP) : Open Close Principle.
  • Liskov Diction Principle (LSP) : Substitution Principle.
  • Interface Segregation Principle (ISP) : Interface Segregation Principle.
  • Dependency Inversion Principle (DIP)

Single Responsibility Principle (SRP)

The SRP requires a single responsibility for each software module, measured by whether the module has only one reason for being modified. The more single the responsibilities, the fewer reasons to be modified, the higher the Cohesion of modules, the more likely they were to be reused and easier to understand.

Open close Principle (OCP)

Software entities should be open for extension and closed for modification. We can implement new requirements as extensions without changing existing functionality.


In object-oriented design, we usually implement OCP through inheritance and polymorphism, that is, encapsulating immutable parts. For the parts that need to change, it is “open” by way of interface inheritance implementation.


In fact, many design patterns are designed to achieve OCP goals. The decorator pattern, for example, extends functionality by wrapping a new class without changing the object being decorated; The policy pattern, by formulating a policy interface, makes it possible to implement different policies; Adaptor patterns that Adapt new functionality without changing existing classes; In observer mode, you can flexibly add or delete observers to expand system functions.

Richter’s Substitution Principle (LSP)

Any parent type in the program should be correctly replaced by the quilt type.


In a parent class, a subclass can override a function of the parent class

Interface Isolation Principle (ISP)

Multiple specific client interfaces are better than one general-purpose interface. The interface isolation principle states that users cannot be forced to rely on interfaces they do not use. In other words, it is better to have multiple specialized interfaces than a single master interface.


Meet the single responsibility principle, so that the responsibility of an interface as simple as possible

Dependency Inversion Principle (DIP)

Interactions between modules should rely on abstractions, not implementations. DIP requires that high-level modules should not depend on low-level modules, and that both should depend on abstractions. Abstractions should not depend on details, details should depend on abstractions.


Dependency inversion allows the previously tightly coupled dependencies to be decoupled, so that both the dependent and the dependent have higher flexibility. (Between two modules, depending on an interface of the other module, do not know its internal implementation)

DRY

DRY is an acronym for Don’t Repeat Yourself. The DRY principle refers to avoiding duplicate code in programming and computation, reducing flexibility and simplicity of code.


Many principles and rules of practice are created to control and eliminate duplication.

The Rule of Three

The rule of three is that when a feature appears a third time, it is necessary to “abstract” it.

KISS principle

KISS (Keep It Simple and Stupid), thought similar to SRP. True simplicity is not not thinking, but first diverging and then converging. In the complex, reasonable split into simple sub-problems.

Level of Abstraction Consistency (SLAP)

The statement in the function satisfies a Single Level of Abstraction Principle (SLAP), and when things from different levels of abstraction are put together, it feels messy and logically dissonant.

Function usage summary

  1. Encapsulate one thing.
  2. Encapsulating judgment, in the case of multiple conditional judgments
  3. Two, three, and more times need to extract the function.
  4. Use the composite function pattern. When a function is too large and too long is a classic code “bad taste,” meaning that the function may be carrying too much responsibility, it is necessary to “divide and conquer” by breaking up the large function into smaller, easy-to-read, and maintainable functions.
  5. Separate functional code from business code. Never use try/catch to print error logs all over the business process. This will entangle the functional code with the business code, clutter the code, and affect the readability of the code. Functions should only do one thing, and error handling should also be one thing.

We refine the function as far as possible is pure function, no side effects, not random modification by external factors. In functional programming, higher-order functions play a dominant role and can bring a lot of flexibility and convenience.

Pure functions

Returns the same output value for a given input parameter.

Higher-order functions

The input arguments are functions, and/or the output values are functions

Improve code quality

  1. Follow rules and principles
  2. Quadratic reconstruction optimization
  3. Test-driven development

Elegant code rarely takes shape in one go, but in most cases is created twice, first to implement functionality and second to refactor and optimize. Optimization should be a part of our coding work, divided into two steps, mainly to consider the efficiency of coding.


Finally, I hope we can all be craftsman and write high quality code

reference

The relevant books

  1. The road to code refinement
  2. Clean Code
  3. Refactoring improves the design of existing code