I read the readable code, so make a note

Since I started working as an inexperienced engineer, I read the readable code, so that memo.

[* Readable Code * Amazon Purchase Link](https://www.amazon.co.jp/%E3%83%AA%E3%83%BC%E3%83%80%E3%83%96%E3%83 % AB% E3% 82% B3% E3% 83% BC% E3% 83% 89-% E2% 80% 95% E3% 82% 88% E3% 82% 8A% E8% 89% AF% E3% 81% 84% E3% 82% B3% E3% 83% BC% E3% 83% 89% E3% 82% 92% E6% 9B% B8% E3% 81% 8F% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E3% 82% B7% E3% 83% B3% E3% 83% 97% E3% 83% AB% E3% 81% A7% E5% AE% 9F% E8% B7% B5% E7% 9A% 84% E3% 81% AA% E3% 83% 86% E3% 82% AF% E3% 83% 8B% E3% 83% 83% E3% 82% AF-Theory-practice-Boswell / dp / 4873115655 / ref = sr_1_1? adgrpid = 52747835709 & dchild = 1 & gclid = CjwKCAjw2Jb7BRBHEiwAXTR4jcm6iePgNgKHDmEvEtkvsB5IJ_skZ0aSoztpmqccbdEWkPh9VInvSRoC2DQQAvD_BwE & hvadid = 338561722060 & hvdev = c & hvlocphy = 1009309 & hvnetw = g & hvqmt = e & hvrand = 10166295044081564502 & hvtargid = kwd-334307148361 & hydadcr = 16038_11170849 & jp-ad-ap = 0 & keywords =% E3% 83% AA% E3% 83% BC% E3 % 83% 80% E3% 83% 96% E3% 83% AB% E3% 82% B3% E3% 83% BC% E3% 83% 89 & qid = 1600565375 & sr = 8-1 & tag = googhydr-22)

It's not a rough note, but a little detailed note!

Chapter 1 Easy-to-understand code

Point

The code should be easy to understand.
The code should be written so that others can understand it in the shortest amount of time.
It's important to have a code that is easy for you to understand after 6 months!
It's better to keep the code short, but it's important to shorten the time it takes to understand.

Is this code easy to understand?

It is important to take a step back and ask yourself!

Chapter 2 Packing information in the name

Point

Pack information in the name

Try to read information just by looking at the name

・ Choose a clear word → Avoid empty words. "Get" is not a very clear word. I don't know where to get?

For example, use fetch / download depending on the situation instead of get.

Avoid generic names

→ Avoid empty names such as tmp and foo. Give it a name that represents a specific purpose or value. Return value retval × sum_squares○

So, when using a generic name such as tmp / it / retval, be prepared for a good reason! It's nonsense to use this just for negligence! "Naming power"!

Use concrete names rather than abstract names

→ Use a more appropriate name

Add information using suffixes

→ If it is important information that you absolutely must inform, you can add it to "Variable name". The unit of value is clearer than delay → delay_secs. The same is true in terms of security. password → plaintext_password (password is plain text and should be encrypted before processing)

Add attributes where you need to understand the meaning of variables.

Determine the length of the name

→ It's simply hard to remember, it occupies the screen, and the amount of code increases. A short name is fine as long as the scope is small. If the scope of the identifier is large, the name needs to be packed with enough information to clarify it. It's easy to omit it, but project-specific abbreviations are not acceptable. I can't understand the new members.

Communicate information in name format

→ You can also use underscores, dashes, and capital letters to stuff information into names. The team decides what rules to use. Consistency is important.

For example, underscore class member variables to distinguish them from local variables.

Chapter 3 Names that are not misunderstood

Ask yourself, "Isn't the name mistaken for another meaning?" Actively search for misunderstandings.

Use min and max to include limits.

Use first and last to specify the range.

Use begin and end for inclusive / exclusive ranges.

Clarify the meaning of true and false when choosing the name of a Boolean variable or a function that returns a Boolean value. Dangerous example bool read_password = true; There are two interpretations ・ Password needs to be read from now on -The password has already been read.

Here, it is better to use need_password instead of read.

Summary

The first name is that the person reading the code can understand your intentions correctly. Before deciding on a name, make sure that the name is not misunderstood by thinking about dissenting opinions. Also pay attention to the user's expectations for the word. Example: Get () and size () are expected to have lightweight methods.

Chapter 4 Beauty

A good code should be "eye-friendly".

Three principles • Use a layout that is consistent with the patterns your readers are accustomed to. -Make similar codes look similar. -Make related codes into blocks.

Obviously, a nice looking code is easier to use. If you can scan it quickly, you can create code that is easy for anyone to read.

A good looking code can improve not only the surface but also the structure of the code.

Keep the vertical lines straight

Aligning the columns can make the code easier to read. Doing this will make it easier to find typos.

Group declarations into blocks

→ In order to get a quick overview of the code, you can divide it into groups and create "units". Easy-to-understand code.

However, it's important to note that consistent styles are more important than "correct" styles. Even if you write it correctly and easily, if you write it in a disjointed style as a whole, it will be difficult to see and read.

Summary

"Shaping" your code in a consistent and meaningful way makes it quick and easy to read.

・ If you are doing the same thing with multiple code blocks, make the silhouette the same person ・ If you arrange the "columns" of the code, it will be easier to get an overview. ・ What was lined up like A / B / C in one place should not be lined up like B / C / A in another place. Choose a meaningful order and always keep that order -Use blank lines to divide large blocks into logical "paragraphs".

Chapter 5 Know what to comment

Valuable and non-valued comments
Do not write information that is immediately apparent from the code.
Do not write comments for comments.

Terrible names change names without comment → Comments are not meant to make up for terrible names. If so, change it to a clearer name.

So what should I write as a comment? → Good comments are for "recording your thoughts". You should write "important thoughts" when writing code

You can comment on why the code is dirty. A comment that encourages someone to fix it.

Let's comment on the flaws in the code.

→ Feel free to comment on what you want to do with the code. → Can inform the quality of the code and indicate the direction of improvement.

Comment on the constant.

→ When defining a constant, what does that constant mean? There is often a background as to why they have that "value". → It is important to record in the comments what you thought in your head when you decided on the name of the constant.

Think as a place for readers to stand
Imagine being asked a question.

Add a comment there to clarify the answer.

Announce a trap that seems to be addictive.

→ Predict the problems you will face when using the code in advance and announce them in the comments.

Overview comments

You have to get the new team members to understand the code. How do the classes work together? Such This is a comment to write in the code.

A short, appropriate document is fine. Better than nothing.

Summary comment

Comments that nicely summarize the low-level code are also important.

Excellent code> Terrible code + excellent comment

Write anything that helps you understand the code!

Overcome Writer's Block

Writer's block = I'm stuck and can't write

The only way to get over this is to start writing. Write down what you think and leave it as a comment. 3 steps to write a comment

  1. Write down the comments in your head anyway.
  2. Read the comments and find out what needs improvement.
  3. Improve.

Summary

The purpose of the comment is to help the reader understand the intent of the code.

Things you shouldn't comment on

・ What can be extracted from the code ・ "Auxiliary comment" to supplement terrible code → Correct the code instead of writing a comment

Things to comment

My thoughts to record · Write why the code looks like this instead of the other way around -Indicate code defects using notations such as TODO :, XXX: ・ Background related to constant values

Think from the reader's point of view ・ Add a comment in anticipation of what the person reading the code thinks "What?" -Document behaviors that surprise the average reader -Write "big picture" comments in files and classes -Comment the code block to summarize it so that the reader is not obsessed with the details.

Chapter 6 Comments are accurate and concise

How can I write it accurately and concisely? Comments should have a high ratio of information to the area.

Keep comments concise

Should I explain using three lines? → If you can explain in one line, use one line.

Avoid ambiguous pronouns

I don't know what "it" or "this" means. For example //データをキャッシュに入れる。ただし先にそのサイズをチェックする。 I don't know what "that" means in this case. It's confusing, so it's easier to understand if you put the noun in the pronoun.

//データをキャッシュに入れる。ただし先にデータサイズをチェックする。

Polish crisp sentences

Accurate comments and conciseness are often compatible.

Example

//これまでにクロールしたURLかどうかによって優先度を変える ↓ //これまでにクロールしていないURLの優先度を高くする

The bottom is simple, short and direct.

Write the intent of the code

Comments that just write the behavior of the code as it is ✖︎

Write in the comments what you were thinking when you were writing the code. This makes it easy to notice that the code and comments are inconsistent (so-called bugs). Comments play the role of redundancy check.

Summary

Write a comment packed with as much information as possible in a small area

・ Avoid pronouns such as "it" and "this" that may refer to multiple things -Explain the operation of the function as accurately as possible -Carefully select I / O examples to include in comments · Code intent is written at a high level, not a level of detail -Use inline comments for unclear arguments. ・ Keep comments concise with words and expressions that are packed with many meanings.

Chapter 7 Make the control flow easier to read

Make code control flow easier to read

Make the control flow such as conditions and loops as "natural" as possible. Write so that the reader of the code does not stop or read back!

Order of arguments of conditional expression

if (length >= 10)

Or

if (10 =< length)

Obviously the first one is easier to read.

There is a guideline for this.

Left side → "Survey target" formula. Change. Right side → "Comparison target" formula. It doesn't change much.

It's the same as English usage.

If / else block order

There are superiority and inferiority in the order

・ Use affirmative system rather than negative condition form. For example, use if (debug) instead of if (! Debug). ・ Write simple conditions first. It is easy to see because if and else are displayed on the same screen. ・ Write the conditions that attract attention or stand out first

Depending on the situation, there may be a conflict, in which case it is at your own discretion.

Ternary operator

It has the advantage of being organized in one line, but on the contrary, it is difficult to read and step through with a debugger.

Shorten the time it takes others to understand rather than shorten the number of lines

Basically use if / else statements! Use the ternary operator only when it simplifies!
Return quickly from function

Some people think that you shouldn't use multiple return statements in a function, but that's wrong. It's good to return quickly from the function.

Make the nest shallow

Deeply nested code is hard to understand. Look at the code fresh when you make changes. Take a step back and look at the whole thing.

Can you follow the flow of execution?

Using components makes it difficult to follow the code. Thread → I'm not sure which code will be executed when. Signal / interrupt handler → Other code may be executed. Exception → Various function calls are about to end

Using these components can make your code easier to read and less verbose, on the other hand. If you don't use it properly, you will lose track of the code.

Chapter 8 Dividing a huge formula

Divide the huge formula into pieces that are easy to swallow

Watch out for "smart" codes. Later, it becomes confusing when others read the code.

It is difficult to understand a huge formula at once. The easiest way to do this is to introduce "explanatory variables" Explanatory variables that hold the values of large expressions have three advantages ・ A huge formula can be divided · You can document your code by explaining the expression with a concise name · Makes it easier for readers to recognize the main "concepts" of the code

Another option is to use De Morgan's laws to manipulate logic.

If you see complicated logic, split it aggressively!

Chapter 9 Variables and readability

Delete variable

The code removes variables that are not readable. → The code will be concise and easy to understand.

Reduce the scope of variables.

It is correct to avoid global variables. → It is difficult to track where and how it is used. It's a good idea to "shrink the scope" of all variables, not just global variables.

Reduce the number of lines of code that you can see the variable as much as possible.

It is said that access should be restricted as much as possible to reduce the code that makes variables visible. → Why? Because you can reduce the variables you have to think about at once

Write variable only once

→ Variables that "do not change permanently" are easy to handle.

The more places you manipulate variables, the harder it is to determine the current value.

Summary

The variables of the program will increase quickly and will eventually become untraceable Code is easier to read if you reduce variables and make it as light as possible

・ Delete disturbing variables -Make the scope of the variable as small as possible → Move to a position that can only be seen from a few lines of code of the variable. -Use a variable that is written only once → If you set a value for the variable only once (or const,), the code will be easier to understand.

Chapter 10 Extracting unrelated sub-problems

Engineering is the process of dividing a large problem into smaller problems and assembling solutions for each.

This chapter is about actively finding and extracting unrelated sub-problems.

  1. Look at the function or code block and ask yourself, "What are the high-level goals of this code?"
  2. Ask each line of code, "Does the high-level goal have a direct effect? Does it solve an unrelated sub-problem?"
  3. If there is a considerable amount of code that solves irrelevant sub-problems, extract them into another function.

Recommended Posts

I read the readable code, so make a note
I read the "Object-Oriented Practical Guide", so a memorandum
I stumbled when I tried using neo4j in the jenv environment, so make a note
I passed the Java test level 2 so I will leave a note
[JAVA] Project Euler, I got stuck in Q8, so make a note
I was a little addicted to the S3 Checksum comparison, so I made a note.
A note about the scope
I read the Kotlin startbook
I tried JAX-RS and made a note of the procedure
I was inspired by the article for newcomers, so make a note of it so that you don't forget your original intentions.
I want to make a button with a line break with link_to [Note]
I read the source of ArrayList I read
I read the source of Integer
I read the source of Long
[Java] I tried to make a maze by the digging method ♪
I read the source of Short
I read the source of Byte
I read the source of String
[Java beginner] I got a little deeper understanding of "It's time to use new", so make a note
Make a note of Ruby keyword arguments
ViewComponentReflex A note I saw by touching
A note on the libGDX Utils class
A review note for the class java.util.Optional
A review note for the class java.util.Objects
A rudimentary note on the Fibonacci sequence
A review note for the package java.time.temporal
Why was the code painful to read?
A note that I gave up trying to make a custom annotation for Lombok
03. I sent a request from Spring Boot to the zip code search API
The training for newcomers was "Make an app!", So I made an app for the time being.
[Small story] I tried to make the java ArrayList a little more convenient
I searched for a lightweight framework that answers the sudden "make it quickly"
A memorandum to clean up the code Ruby
Make a margin to the left of the TextField
I did Java to make (a == 1 && a == 2 && a == 3) always true
A note when the heroku command becomes unavailable
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
The code I used to connect Rails 3 to PostgreSQL 10
[API] I tried using the zip code search API
I built a Code Pipeline with AWS CDK.
Make a snippet for Thymeleaf in VS Code
A note about the Rails and Vue process
[Ruby] I want to make a program that displays today's day of the week!
I wrote a test code (Junit & mockit) for the code that calls the AWS API (Java)
I hate this kind of code! A collection of anti-patterns actually seen in the field
7 things I want you to keep so that it doesn't become a fucking code
kintone clone? I was quite addicted to launching OSS WebDB Extension with Lightsail + Docker, so make a note of it.