"The art of Writing readable code" reading notes
Objective
This book is designed to help you write better code
1th Chapter code should be easy to understand
What makes the code "better"
Basic theorem of readability
The code should be written so that others can understand the time it takes to minimize it.
Is it always as small as possible?
Minimizing the time required to understand the code is a better goal
Whether the time required to understand the code conflicts with other targets
It doesn't even affect each other.
The hardest part.
Often think other people will think your code is easy to understand and need extra time
The first part surface level improvement
Choose a good name, write a good note, and put the code neatly in a better format
The 2nd chapter puts the information in the name
Choose a professional word
The term distinguishes its function and finds more expressive words.
Avoid generic names like TMP and reveal.
A good name should describe the purpose of the variable or the value it carries
If you need to use a vague name like TMP, lt or retval, then you have a good reason
To take a specific name for an abstract name
When naming a variable, function, or other element, describe it more concretely rather than more abstract.
Attach more information to the name
If there is anything important about a variable that the reader must learn, it is worth adding the extra word to the name.
Values with units, additional important attributes attached
How long should the name be?
The name can't be too long.
Short names can be used in small scopes.
Entering a long name ———— is no longer a problem (the word completion feature of the editor)
Acronyms and abbreviations
Throw away the useless words
Use the format of a name to convey meaning
Hump class name, underscore method name, constant hump plus kconstant prefix, macro is all uppercase underline participle, constructor letter uppercase, jquery object plus $
Destination use case, underline, etc.
The 3rd chapter will not misunderstand the name
Ask yourself a few more times: "Will this name be interpreted by others as something else?" ”
Example: Filter ()
Ambiguous words, do not know the meaning of "pick out" or "Lose"
Example: Clip (text,length)
A semantic word, which may be removed from the tail, or may be cut out for a length of
It is recommended to use first and last to represent the included range
The clearest way to name limits is to add Max or minto the things you want to limit.
It is recommended to use begin and end to denote inclusion/exclusion ranges
To name a Boolean value
When choosing a name for a Boolean variable or a function that returns a Boolean value, make sure that the meaning of true and false returns is clear.
It is best to avoid the use of antisense names. such as ' Disable_ssl '.
Match the expectations of the user
Some names can be misunderstood because users have a preconceived impression of what they mean, even if that's not the way you intended it to be. In this case, it is better to give up the name and use a name that will not be misunderstood.
Example: How to weigh multiple alternative names
Analyze each alternative name and consider the various possibilities that are misleading.
4th Chapter Aesthetic
Making the code easier to read has three principles:
. Use a consistent layout so that readers get used to this style quickly. Make similar code look similar. Grouping related lines of code to form blocks of code
Why is aesthetics so important
Pleasing code is easier to read
Rearranging line breaks brings consistency and compactness
Use a method to sort out irregular things.
Making the code "look good" usually brings an improvement that is not limited to surface level, it may help you to make the code more structured.
Use column alignment when needed
Choose a meaningful order and always use it consistently
With a lot of get parameters to get, we have some ideas for each order in the code that we get:
. Make the order of the variables with the corresponding HTML formMatch the order of the fields. From "most important" to "least important". Sort by alphabetical order
5th Chapter Rewrite what kind of comment
The purpose of the note is to try to help the reader to understand as much as the author
What doesn't need a comment
Do not write comments for facts that can be inferred quickly from the code itself
Do not annotate for comments
Don't comment on bad names ———— should change their names.
Record your thoughts.
Have important ideas when writing code
Standing in the reader's shoes
Imagine what your code looks like for outsiders.
To announce a possible trap
Holistic annotation, taking into account the newcomers, let her familiarize herself with the code base
The last thought ———— overcoming "the author's mental retardation"
The 6th Chapter writes the Concise comments
Comments should have very high information/space rates
Keep Annotations Tight
Avoid the use of ambiguous pronouns
such as it, this
To polish a rough sentence
Accurately describe the behavior of a function
Return the number of lines in this file and count how many newline bytes (' \ n ') is in the file
Use input/output examples to illustrate special situations
Example
Intent to declare code
What are want do
Comment for named function parameter
Default parameter connetc (timeout = ten, user_encryption = False)
Do not, with connet (/* timeout_ms= * *,/* use_encryption = */False)
Use words with high information content
If you feel that a comment is too long, then you can see if you can describe it in a typical programming scenario.
Part II simplifies loops and logic
Try to minimize the "mental burden" in the code
The 7th chapter is easy to read the control rheology
The more "natural" the conditions, cycles, and other changes to the control flow, the better. Use a way to make the reader not stop and reread your code
Order of reference in conditional statements
Compare the left side of the comparison to the right of the "queried" expression, which tends to change the expression used to make comparisons, and its values tend to be constant
If/else the order of statement blocks
. It first deals with the case of positive logic rather than negative logic. For example, use if (debug) instead of if (!debug): Get rid of the simple case first. This approach may also make the if and else visible within the screen. To deal with interesting or questionable situations first.
?: conditional expression (also known as "trinocular expression")
A better measure than the pursuit of minimizing the number of lines of code is to minimize the time that people need to understand it.
By default, If/else is used. Trinocular operator?: Used only in the simplest case
Avoid do/while loops
My experience is that do statements are the source of errors and confusion ... I tend to put the conditions "where I can see before". As a result, I tend to avoid using do statements.
Returning early from the function
The infamous goto
You should avoid using goto
Minimize nesting
Deep-Nested code is hard to understand.
When you make changes to the code, look at it from a new perspective and look at it as a whole
Reduce nesting by early return
Can you understand the process of execution?
Don't let the code use threads, semaphores, exceptions, function pointers and anonymous functions, or virtual methods too much to make the implementation process a lot more difficult to understand.
8th Chapter Split the extra long expression
Split your extra-long expression into smaller pieces that are easier to understand
Variables used as explanations
Temporary intermediate variable
Summary variables
Using the Demogan theorem
To reverse, convert and/or
Misuse of short-circuit logic
Beware of "smart" small code ———— they tend to confuse others later.
Example: Battle with Complex logic
struct range{ int begin; int end; For example,[0,5) overlaps with [3,8] bool Overlapswith (Range other);
Opposite comparison
BOOL Range::overlapswith (Range other) { if (other.end <= begin) return false; if (other.begin >= end) return false; return true;}
Splitting a huge statement
Extract common parts into functions as summary variables
Another creative way to simplify expressions
Defining macros
The 9th chapter variables and readability
The more variables, the more difficult it is to keep track of their movements.
The larger the scope of the variable, the longer it needs to be tracked.
The more frequently a variable changes, the more difficult it is to track its current value
Reduce variables
Temporary variable with no value
Reduce intermediate results
Reduce control Flow variables
Narrowing the scope of a variable
Make your variables visible to as few lines of code as possible.
A variable that writes only once is better
The more places you manipulate a variable, the harder it is to determine its current value.
The last example
Part Three reorganize the code
Greater changes to the code at the function level
The 10th chapter extracts irrelevant sub-problems
Look at a function or block of code and ask yourself: What is the high-level goal of this code?
For each line of code, ask: does it work directly for the goal? What is the high-level goal of this code?
If sufficient functions are in the solution of unrelated sub-problems, extract the code into a separate function.
Separate generic code from project-specific code
An introductory example: Findclosestlocation ()
Pure Tool Code
Miscellaneous Multi-purpose code
The child code calls itself one after the other to improve it easier
Create a large number of common code
The generic code is good because "it's completely decoupled from the rest of the project"
Project-specific features
Simplifying an existing interface
You never have to be comfortable with an undesirable interface.
Reshaping interfaces On Demand
Overkill
Do not divide too thin, multiple small functions for readability disadvantage
The 11th chapter is one thing at a time.
You should organize your code once to make one thing.
The task can be very small
Examples of voting
Extracting values from an object
A larger example
The 12th chapter turns ideas into code
If you can't explain something to your grandmother, it means you haven't really understood it yet.
To clearly describe the logic
Describe logic in natural language
Understanding function Libraries is helpful
Part of the job of writing refining code is to understand what your library provides.
Apply this method to a larger problem
Natural language description logic, appropriate recursive call itself
13th chapter Less Code
The best code to read is no code.
Don't bother to implement that function ———— you don't need it.
Questioning and splitting your needs
Keep Small code base
Make your codebase smaller, the lighter the better
Remove the useless code
Familiar with the library around you
Spend 15 minutes every other time reading the names of all functions/modules/types in the standard library
In a mature library, each line of code represents a lot of design, debugging, rewriting, documentation, optimization, and testing.
Example: Using UNIX tools rather than writing code
Avoid writing new code by using the following methods:
. Eliminate unnecessary functionality from your project and do not overdo it.
. Reconsider the requirements, solve the simplest version of the problem, as long as you can complete the work.
. Constantly read through the entire API of the standard library to keep them familiar.
Part IV Featured Topics
14th Chapter Test and readability
Make testing easy to read and maintain
The test should be readable so that other programmers can comfortably change or increase the test
What's wrong with this test?
Make this test more readable
To hide unimportant details from the user so that more important details will be more prominent
Create a minimal test declaration
The basic content of most tests can be refined to "expect such behavior/output for such input/output scenarios"
Implementing a customized "micro-language"
Make error messages readable
Understanding libraries that display errors
Manually create error messages
The more helpful the error message should be, the better.
Select a good test input
The basic principle is that you should choose the simplest set of inputs that can be used to fully use the code under test
A better test value for simple and complete work
Multiple tests of a feature
Name the test function
Test_ _ ()
What's wrong with that test?
A better way to develop the test
You will begin to write the code easy to test!
Go too far.
. Sacrificing the readability of real code just to enable testing. Fascinated by the 100% test coverage. Making testing a hindrance to product development
The 15th chapter designs and improves the "minute/hour counter"
Problem
Track how many bytes the Web server has transmitted over the past minute and one hours.
Defining class Interfaces
Try 1: a naïve scheme
Try 2: Belt Design Solution
Try 3: Time Bucket design scheme
Compare three different scenarios