Hello everyone, my name is Xie Wei, I am a programmer.

Besides my regular job, I also have a hobby in powerpoint presentation design. As I wrote more code and made more slides, I realized more and more that a lot of things were connected.

That explains why so many people are so good at so many things. Is it not because of mastery of the underlying essence?

Why do catchy catchphrases spread more widely?

Why is good copy concise enough to get users’ attention?

Why do rumours spread more widely?

Yes, they must have accurately captured the user’s psychology.

This article explains the art of writing readable code with some simple design guidelines.

“Design book for everyone” in the full text of the interpretation of the four norms of design: intimacy, alignment, repetition, contrast. The Art of Writing Readable Code explains the art of writing readable code: Make it easy to understand.

Yes, there are many excellent designers in the market, designing works that are elegant enough and understandable to users in seconds. A good designer must be well versed in psychology.

Writing code is in essence combing logic. In order to improve the whole logical process, we borrow variables, functions, flow control, loops, notes, methods and so on from programming languages to connect them together to improve a set of system logic.

To complete this logic, we use many tools: design methodology, architectural design, project organization, etc.

Realize that, to some extent, good code can be judged logically.

  • Logical, not necessarily optimal code
  • It’s not logical, it’s definitely not good code

From this point of view, it is extremely important to tease out the logic. Once the logic is clear, all that remains is implementation.

Logic is connected by programming language variables, functions, flow controls, loops, comments, etc.

This article describes how to write readable code from these perspectives.

0. Specification

The vast majority of people do not complete a complex project from scratch, most of the team work together to complete a large project.

At this point, if you’re in the middle of something. When you implement logic, do you follow your own logic or do you follow the team’s style?

Like project organization, naming, etc…

Follow the team style

Especially for complex on-line projects, it is difficult to understand the whole project completely. At this time, the unity of style is especially important.

Yes, style consistency is important at this point, but of course the specific implementation logic should follow the general direction of ease of understanding.

1. Programming language specifications

Rule: Stick to your programming language style

For every programming language, there are certain specifications, such as Python’s underlined variable command rules, Go’s camel variable command rules, and so on.

At this point, the overall specification of the programming language needs to be followed.

You might want to look at the various programming language specifications that Google produces. It’s the right direction.

Named after 2.

  • variable
  • function
  • methods

Rule: Easy to understand

How to make it easy to understand:

  • Professional words: Use words in your field
  • Avoid generic names
  • Specific name
  • Variable names with more detail
  • Don’t use misleading names
  • Boolean value naming
  • Words not recommended

2.1 Words in the domain

This is related to the project. For example, the system is an intelligent retail background, and the words in the field are: customer, commodity, shop, assistant, store manager, price, etc.

  • customer
  • produce
  • shop
  • shopLeader
  • price

2.2 Avoid generic names

Variables are usually named with some meaning, and in rare cases, words that have no meaning can be used. Like the most common:

var (
    numberOne int
    temp int
    numberTwo int
tmp = numberOne
numberOne = numberTwo
numberTwo = tmp

Copy the code

Such as:

var i int

fori=0; i<10; i++{ fmt.Println(i) }Copy the code

This kind of meaningless word generally applies to local scopes.

Use as little as possible.

2.3 Specific name

Use the words to accomplish the task. Most variables use nouns and most functions start with verbs.

Functions use verbs and variables use nouns

Such as:

var toString = func(){}

var serverLoop = func(){}

var pages int 

var userName string
Copy the code

2.4 With more details

General naming is not recommended too long, also not recommended too short, that how long, how short is appropriate?

The maximum length is three words

How to bring more details.

  • Try using suffixes
  • Try using units
  • Try pointing to specific details

Such as:

var timeIntervalMs

var lengthCm

var delaySecs

var sizeMb

var maxKbps

var degreesCw

var numberMax

var numberMin

var numberFirst

var numberLast

Copy the code

Give suffixes for sets of antitheses:

  • max/min
  • first/last
  • begin/end …
ServerCanStart CanListenOnPort than () ()Copy the code

2.5 Don’t use misleading words

For example, Filter is easy to use in database operations. This word does not carry more details. In fact, in the process of use, you still need to check the WRITTEN SQL statement to know the specific filtering details. A few more steps of holistic thinking. Not easy to understand.

It is recommended to read the words you name several times

2.6 Boolean value

Boolean values, because there are two outcomes. All, generally use words with or without such meaning.

Such as:

var (
    ok bool
    notOk bool

var (
    is bool

var (
    has bool

var (
    found bool

var (
    should bool

var isCompany = func(){}

var isVip = func(){}

var hasSpace = func() {}Copy the code

2.7 Words not recommended

  • get
  • read
  • util

These are the words that are easiest to use when writing code. Choose alternatives.

Present a wave word:

- Send deliver, dispatch, announce, distribute, route-find search, extract, locate, recover-start launch, create, begin, open - make the create,setUp, build, generate, compose, add, newCopy the code

3. The design

What does a good slide presentation design take into account?

  • Match the color scheme of the scene and set the original tone
  • Things that fit the scene, borrowed to express ideas
  • Unified overall style
  • Align, repeat, intimacy, compare

See, the slide show design, emphasize the scene, choose the subject and color suitable for the scene, such as party and government style, of course, choose the national flag color; For example, academic defense, of course, choose blue; Like the mobile press conference, of course, using dark tech style…

So the code also needs to be scenarioized, selecting words that fit the scene, etc

The four specifications for design are used here as an analogy to code organization.

3.1 the alignment

Why do programming languages emphasize indentation? Isn’t it to make it easier for people who read the code to understand it? Is it easier for people who write code to organize it? Is it just for fun?

Of course not.

Example: Write web routes and controllers

// student.go

func Register(r *gin.Group) {
    r.POST("/v1/api/students", PostHandler)
    r.GET("/v1/api/students/:sid", GetHandler)
    r.PATCH("/v1/api/students/:sid", PatchHandler)
    r.PUT("/v1/api/students/:sid", PutHandler)
    r.DELETE("/v1/api/students/:sid", DeleteHandler)

Copy the code
  • Do you know what to accomplish when you look out
  • The style is unified
  • neatly

This example may explain alignment, not friendly enough.

Here’s another example:

CheckFullName("No Such Guy".""."not match found")

CheckFullName("John".""."more than one resule")

Copy the code

3.2 Repetition, intimacy and comparison

Of course, as a programmer, the most important thing to avoid is to write repetitive code, the general practice is to play with abstraction, the repetition of the abstraction into a function and so on. The repetition here is the unity of style

// teacher.go

func Register(r *gin.Group) {
    r.POST("/v1/api/teachers", PostHandler)
    r.GET("/v1/api/teachers/:tid", GetHandler)
    r.PATCH("/v1/api/teachers/:tid", PatchHandler)
    r.PUT("/v1/api/teachers/:tid", PutHandler)
    r.DELETE("/v1/api/teachers/:tid", DeleteHandler)


Copy the code

Student. Go and teacher. Go

This way of organizing, in a sensible way, is not too much of a cognitive burden on the person reading the code.

  • Consistent order
  • Always consistent use, users actually read a similar can understand in seconds

3.3 white space

Design field page design, do not emphasize the content of the more the better, appropriate blank on the page, so that the overall design has a sense of breathing.

So how does programming implement white space?

  • Appropriate line breaks make similar content more compact
  • Extract, use methods to organize irregularities
  • The code fragment

If you need to write more than 100 lines of a function, I’m probably advising you not to do that, sorry.

  • Split, logical sorting, extraction methods
  • Try to maintain a maximum of 30-50 lines (so that the screen can load the entire function logic in one sitting).


Rule: The person who helps read the code knows as much about it as the person who writes it

  • When do I not need comments
  • When do I need comments

4.1 When are comments not needed

Yes, the previous set of rules, naming and so on, are content and comments, reading variables, function names and so on to understand what the code does.

There is no need for comments in such a place, because it is obvious that facts can be inferred from the code itself.

There may be times when you need to consider whether naming is bad enough to require annotations, and in that case naming is preferable to annotations.

Commenting bad code can be just as scary as continuing to work on the wrong path.

4.2 When are comments needed

  • The key point
  • Point defects
  • constant
  • Global annotation
  • Summary notes

Key points:

Sometimes, just relying on the previous “surface work” is not enough to make people understand. At this point you need to add comments at key points.


Yes, acknowledge that your code is not optimal, just implementation, and that there is a better way to do it, so you need to add comments where there are weaknesses.

Constants :(uppercase constants are recommended for each programming language)

Constant comments are given more meaning.

Such as:

NUMTHRADS = 8 // as long as it is >= 2 * number_processors, that is good enough.
Copy the code

Okay, so if you’re tuning your code and you see this comment, yes, you know how to tune it.

Global comments:

Usually at the beginning of the file, indicating the task accomplished by the code in the file.

Summary notes:

The beginning of a normal function indicates what the function code does.


Polish the statement. To the point because of a lengthy explanation. (These seem to require a lot of writing skills)

5. To summarize

Suggestions for writing readable code are given “on the surface”, and the next article covers suggestions for writing readable code from the perspective of processes, loops, abstractions, organizational code, and so on.

See you next time. I’m Xie Wei.

thank you