Reading Notes while keeping code clean; Reading Notes

Source: Internet
Author: User
Tags define exception

Reading Notes while keeping code clean; Reading Notes



Chapter 4 clean code
1.1 code required
1.2 bad code
Never after
1.3 if you do not pay attention to the cost of chaos in the early stage, the efficiency of code addition and modification in the later stage is very low.
1.3.1 gorgeous new design
1.3.2 attitude
1.3.3 questions
1.3.4 clean code
1.3.5 what is clean code
1.4 schools of thought 1.5 The time for the author to read and write code may be. You can use the playback function of the editor to view your own writing records 1.6.
1.7 prerequisites and principles




Chapter 2 meaningful naming
2.1 Introduction
2.2 The name of a variable is too casual. haha, list1, and OK are meaningless. 2.3 avoid misleading keywords such as List, letter o, and number 0.
2.4 make a meaningful teaching material to distinguish the opposite. The variable names are a1, a2, and a3 to avoid redundancy, do not show Variable or table fields. Do not use tables or strings. Do not use NameString-Direct Name. 2.5 use the read Name. Do not use words that you have pieced together, use complete words whenever possible
2.6 Use searchable names for some constants. Instead of using numbers directly, specify a variable name. This variable name can be easily searched.
2.7 avoid Coding
2.7.1 The Hungarian markup method does not use abbreviations like this
2.7.2 avoid using a prefix for a member. However, in Android, it is better to use m to indicate a private prefix.
2.7.3 interfaces and implementations do not like to start with I. The implementation also hopes to add imp
2.8 avoid using simple a, B, and c to reduce the number of words by 2.9 Class names
The class name and object name should be TermAnd Noun Phrase, Cannot make a verb. 2.10 method name the method name should be a verb or verb phrase without using the constructor, but using the corresponding public (the constructor is too common and it is also time consuming to name these parameters, so I don't agree.) 2.11 don't pretend to be cute. Some variables are haha and banana.
2.12 why does one concept correspond to Control and Manager in a word project?
2.13 It is not appropriate to use add in proportion to insert and apped. Add indicates the complete meaning of the new addition.
2.14 when using the Domain Name of the solution, programmers can view the code. Therefore, professional words can be considered when naming.
2.15 use names originating from the problem areas
2.16 adding meaningful contexts can put relevant variables into a class and use this class to indicate the context.
2.17 do not add project abbreviations in useless context names. This is completely unnecessary.
2.18 last words
The most difficult part to get a good name is the need for good descriptive skills and a common cultural background.


Chapter 2 Functions
3.1 do not write hundreds of rows of functions
3.2 do only one thing and try to ensure that each function does only one thing
3.3 each function reads code from top to bottom at an abstract level: downward rules
3.4 The switch statement puts the switch in the factory. You do not need to consider how to implement the switch.
3.5 use descriptive names 3.6 The number of function parameter parameters should be as small as 3, the less the better 3.6.1 the common form of a one-dimensional function
3.6.2 identify the parameter-if you need to pass true or false to the method, the method must do two things.
3.6.3 binary Functions
3.6.4 ternary Functions
3.6.5 parameter object-if there are too many parameters, you can directly encapsulate these parameters into an object.
3.6.6 parameter list-if multiple parameters can be input, but more than three parameters need to be simplified.
3.6.7 verb and keyword 3.7 methods without side effects may need to be called in a certain scenario to have an ideal result. For example, some can only be called during initialization. You can name the checkPassowrdAndInitializeSession output parameter and change the function content on the input parameter. In this case, try to avoid or use appedFooter (StringBuffer report) such a name
3.8 separate the command and ask if the value of a variable is set in the method and there is a return value, you can name it setAndCheckIfExists3.9 and use an exception to replace the returned error code 3.9.1. Extract the content in the Try block from the try/Catch code block to a method.
3.9.2 error handling is one thing
3.9.3 Error. java depends on the magnet
3.10 do not repeat the code to avoid repeated functions in the project. Remember to copy a function directly to several places for use.
3.11 structured programming functions are short and occasionally return, break, and continue statements are good
3.12 how to write such a function?
Conclusion 3.13
3.14 setupteardown0000der Program
3.15 Literature




Chapter 2 Notes
4.1 comments cannot beautify bad code comments. Apart from the uncertain comments written, you may forget to modify the corresponding comments because of code modifications. As a result, the comments above the Code are not actually the meaning of the following code.
4.2 elaborate with code
4.3 comments
4.3.1 Legal Information
4.3.2 provide comments of Information-add an example that meets the requirements on the regular expression. The returned value is included in the function name.
4.3.3 interpretation of intent-code written in some places may be inconsistent with common sense, but it can be explained with comments because it must be written in a specific environment.
4.3.4 Interpretation
4.3.5 warning-Precautions for code modification.
4.3.6 TODO comments
4.3.7 zoom in
4.3.8 Javadoc in public APIs-you can learn javadoc
4.4 bad comments
4.4.1 muttering-some comments do not clearly explain things, as if they were the extra comments written by the author to myself. 4.4.2-the function code is very simple and easy to understand. However, the comment is very long.
4.4.3 misleading comments-in some special cases, the comments are not described, but the use of functions is not as effective as the comments.
4.4.4 regular comments-every variable name and every function has comments, which is silly.
4.4.5 log-type annotation-added who modified it, but now the code management tools such as SVN can view it
4.4.6 nonsense comments
4.4.7 terrible nonsense
4.4.8 do not use comments when using functions or variables
4.4.9 position mark-use /// to separate some functions, which is not recommended in the book, but I personally feel that this can make the code clearer.
4.4.10 comment behind the brackets-multi-layer nesting. Add the ending brackets of the control keyword at the end of the brackets. In this case, multiple methods can be extracted.
4.4.11 ownership and signature-No need, because there is a source code control system
4.4.12 commented out code-currently unnecessary code can be deleted directly. You can use the source code control system to find the previous version.
4.4.13 HTML comments
4.4.14 non-local information
4.4.15 excessive information-the primary node requires the core information and does not need to be described in a large segment
4.4.16 inconspicuous contact
4.4.17 function Header
4.4.18 Javadoc-public in non-public code must be added to inform users of some information, but the private method is not required in many cases.
4.4.19 example





Chapter 1 format
5.1 purpose of format
5.2 vertical format
5.2.1 it is important to learn from newspapers and read from top to bottom.
5.2.2 code separation in the vertical direction between concepts is usually read from top down, from left to right. There must be no space between functions, in this way, the readability will be better. Variable declaration in the vertical direction near 5.2.4 vertical distance function-global variables in the near-used place-related functions at the top of the class-the functions called by the current function should be vertically put together related Concepts-for example, functions with the same prefix names, or overload functions are put together.
5.2.5 vertical order
5.3 The number of characters in each line of code in horizontal format is unacceptable if horizontal scrolling is required. Therefore, it is recommended that each line contain about 120 characters. Of course, the shorter the length, the better.
5.3.1 add spaces on both sides of the horizontal and near equal signs (=) and between the calculation symbols (*/)
5.3.2 horizontal alignment many variables are aligned on the left side of the variable name. This is nice, but it takes time to process them in a unified format. In addition to appearance, it is not very useful.
5.3.3 indent 5.3.4 if functions with a null range have only one line of content without brackets, which can easily lead to errors in misunderstanding and modification. 5.4 team rules
5.5 Uncle Bob's format rules




Chapter 3 object and Data Structure
6.1 thoughts on how to add these methods to data abstraction setter/getter
6.2 anti-symmetry of data and objects
6.3 Demeter Law
6.3.1 train crash
6.3.2 Hybrid
6.3.3 hidden structure
6.4 data transfer objects
Conclusion 6.5
Exposes objects and hides data.



Chapter 1 error handling
7.1 use exceptions instead of return Codes instead of returning methods. Instead, use the exception mechanism provided by the programming language to intercept them.
7.2 first write the Try-Catch-Finally statement 7.3 to use an uncontrollable exception 7.4 to describe the environment where the exception occurred
7.5 define exception classes as needed by callers
7.6 define general process 7.7 do not return null values return empty strings or empty lists (Collections. emptyList ())
7.8 do not pass the null value to avoid passing in the null value rather than making a judgment in the function (you should make a null judgment in the function. After all, write code together and others will inevitably pass in)
Conclusion 7.9
7.10 Literature




Chapter 3 Boundary
8.1 use third-party code
8.2 browsing and learning boundaries 8.3 learning log4j
8.4 The benefit of the learning test is not just to write a demo for free without fully understanding the functions of an API, but to test whether it is as understandable as you understand it, which is very cost-effective and accurate.
8.5 use existing code to define interfaces, similar to writing test data.
8.6 clean borders
8.7 Literature




Chapter 4 unit test
9.1 TDD three laws 1. Production Code cannot be written before writing unit tests that fail;
2. Only unit tests that just fail to be compiled are not compiled;
3. Only production code that is sufficient to pass the current failed test can be compiled.
9.2 keep testing clean and testing code as important as production code. It needs to be thought, designed, and cared.
9.3 clean test each test shows the BUILD-OPERATE-CHECK Mode.
9.3.1 test languages for specific fields
9.3.2 dual standards
9.4 one assertion for each test
9.5 F. I .R. S.T. Fast: testing should be Fast enough.
Independent: The test should be Independent of each other.
Repeatable: The test should be Repeatable in any environment.
Self-Validating: The test should have a Boolean output.
Timely (Timely) testing should be written in a Timely manner.
Conclusion 9.6





Chapter 1 category
10.1 organizations
10.2 class should be short
10.2.1 It is recommended in the single accrual principle that the system should be composed of many short classes instead of a few huge classes. Each sub-category encapsulates one responsibility and only one reason for modification, which is better than cooperating with a few others to achieve the expected system behavior. 10.2.2 cohesion
10.2.3 maintaining cohesion will produce many short classes
10.3 organize for Modification




Chapter 2 System
11.1 how to build a city to discuss how to maintain cleanliness at a higher abstraction level-system level.
11.2 separate system construction and use
11.2.1 put the main constructor into the main entry?
11.2.2 The factory application needs to determine when the object can be created.
11.2.3 dependency injection can be analyzed, constructed, and used.
11.3 resizing 11.4 Java proxy
11.5 pure Java AOP framework
11.6 AspectJ
11.7 test-driven system architecture
11.8 optimization decisions
11.9 wise use adds a standard that can demonstrate value
11.10 system needs domain-specific languages
Conclusion 11.11



Chapter 2
12.1 achieve cleanliness through iterative design Kent Beck's four rules on "simple design": 1. run all tests 2. repeatable 3. expressed the programmer's intention 4. minimize the number of classes and Methods 12.2 simple design rule 1: Run all tests
12.3 simple design rules 2 ~ 4: refactoring
12.4 repeatable
12.5 Expressiveness
12.6 As few classes and methods as possible
Conclusion 12.7


Chapter 2 Concurrent Programming
13.1 why concurrency
13.2 concurrent execution is unordered and thread security needs to be ensured.
13.3 concurrent defense principle 13.3.1 the method/class/component of a single accrual principle should have only one reason for modification. Suggestion: Separate concurrent and non-concurrent code. 13.3.2 inference: The data scope is limited to synchronized. Remember to encapsulate the data and strictly restrict access to data that may be shared.
13.3.3 inference: Use data replicas to avoid data sharing. The data returned by multiple threads is independent and then merged to the main thread after execution.
13.3.4 inference: the thread should be as independent as possible
13.4 Understand Java library limited resources-there are fixed-size or number of resources in the concurrent environment. For example, the fixed size read/write cache of the database connection box. Mutex-only one thread can access Shared data or shared resource at each time point-one or more threads are permanently disabled for a long time. For example, a fast thread is always run first, for example, a fast thread is endless, A thread with a long execution time will experience a "Hunger" deadlock-two or more threads wait for the execution to end. Every thread has the resources required by other threads, and cannot terminate without the resources of other threads. Live locks-threads with the same execution order, each of which wants to start, but it is found that other threads are "on the road ". Due to competition, the thread will continue to start, but it cannot be started for a long time.
13.5 understand the execution model
* ** 13.5.1 one or more production threads of the producer-consumer model will create some jobs and place them in the cache or queue. One or more consumer threads obtain and complete these tasks from the queue. A queue between producers and consumers is a resource limitation.
* ** 13.5.2 reader-author Model
* ** 13.5.3 banquet philosophers
13.6 be cautious about dependency between synchronization methods to avoid using multiple methods of one shared object.
13.7 keep the synchronization area small
13.8 it is difficult to write the correct code to close the code.
13.9 testing thread code
13.9.1 treat pseudo-failure as a possible thread Problem
13.9.2 enable non-thread code to work first
13.9.3 write pluggable thread code
13.9.4 compile adjustable thread code
13.9.5 threads running more than the number of processors
13.9.6 running on different platforms
13.9.7 device error code
13.9.8 hard Encoding
13.9.9 Automation
Conclusion 13.10
13.11 Literature


Chapter 2 gradual improvement
14.1 how do I implement Args? To write neat code, you must first write dirty code and then sort it out. For example, writing a text, writing a draft, and then writing a text.
14.2 Args: draft
14.2.1 so after I pause and add new columns, I need to modify the code to find out which code needs to be changed. The improved method is to find out the changes: 1. each parameter type must have a parser paradigm element to select the HashMap method for this type. 2. Each type needs to be parsed in the command line string, and then converted to the real type. 3. Each parameter type requires a getXXX method, which returns the parameter value to the caller based on its actual type.
14.2.2 progressive
14.3 string Parameters
14.4 The Junit test has been compiled before the modification to ensure that the system functions will not be affected during each modification. Find the explosive growth point. First, add a variable and perform small-scale modifications step by step. Each change must pass the Junit test.



Chapter 4 JUnit
JUnit framework 15.1
Conclusion 15.2



Chapter 1 rebuilding SerialDate
16.1 first, let it work
16.2 make it right
Conclusion 16.3
16.4 Literature


Chapter 2 taste and Inspiration comments
C1. inappropriate comments
Store inappropriate comments to the source code control system.
C2. discarded comments
Obsolete, irrelevant, or incorrect comments are discarded comments that should not be retained and must be deleted immediately.
C3. redundant comments
Comments should talk about something that the Code does not mention. Otherwise, it is redundant.
C4. bad comments
The comments worth writing must correctly write the best comments. If not, do not write them.
C5. commented out code
The commented out code must be deleted.
Environment
E1. it takes multiple steps to build
Building a system should be a single-step small operation.
E2. tests that require multiple steps
All unit tests can be run with only one command.
Function
F1. too many parameters
The fewer the number of function parameters, the better.
F2. output parameters
The output parameter is directly in violation and the output parameter is resisted.
F3. identification parameters
Boolean parameters are confusing and should be eliminated.
F4. dead Function






Functions that are never called should be deleted.
 
General questions
G1. a source file has multiple languages.
Minimize the number and range of source file languages.
G2. obvious behaviors are not implemented
Following the "least surprising principle", functions or classes should implement the actions that other programmers have to expect. Do not let other programmers see the code to understand the function's role.
G3. incorrect Boundary Behavior
The code should have the correct behavior, trace each boundary condition and perform a comprehensive test.
G4. Security ignored
Pay attention to the code that may cause problems and pay attention to security and stability.
G5. repeated
Eliminate repeated code and use the design mode.
G6. code at the abstract level of the Error
The conceptual model of abstract classes and derived classes must be completely separated. For example, the Code related to implementation details should not appear in the base class.
G7. the base class depends on the derived class.
The base class should have no knowledge about the derived class.
G8. excessive information
The fewer the variables, the better. Hide all the implementations. The fewer open interfaces, the better.
G9. dead code
Find and delete all codes that are not called.
G10. vertical separation
The definition of variables and functions should be close to the called code.
G11. inconsistency
Function parameter variables should be consistent from the end to the end, so that the code can be easily read and modified.
G12. audio-visual
Useless variables, non-called functions, comments without information should be cleared.
G13. human coupling
Something that does not depend on each other should not be coupled.
G14. characteristic attachment






The class method should be only interested in its own methods and variables, and should not be omitted from other class methods and variables.
G15. select operator Parameters
Avoid Boolean parameters and replace them with polymorphism.
G16. obscure intent
Code should be as expressive as possible and clear intent is more important than efficiency and performance.
G17. permission and responsibility for location errors
The "least surprising principle" puts the code in the place that the reader thinks, rather than the convenience for himself.
G18. improper static method
To use a static method, make sure you have no chance to make it vulnerable to polymorphism.
G19. use explanatory variables
Splits the computing process into a series of well-named intermediate values to make the program more readable.
G20. the function name should express its behavior G21. understand the algorithm
G22. change logical dependency to physical dependency
Dependencies should be obvious, rather than hypothetical dependencies.
G23. replace If/Else or Switch/Case g24with polymorphism. Follow the standard convention G25. Replace the magic number g26with a naming constant. Accurate
The ambiguity and inaccuracy in the Code must be eliminated either because of different opinions or laziness.
G27. the structure is more than the agreed G28. encapsulation Conditions
Encapsulate conditions into methods.
G29. avoid negative conditions
Use affirmative conditions.
G30. the function only needs to do one thing. G31. masking timing Coupling
Create an ordered queue to expose Time Series Coupling. Each function generates the parameters required by the function to ensure the correct time series.
G32. do not feel free






The Code cannot be random and you need to consider it with caution.
G33. encapsulate Boundary Conditions
For example, the + 1 or-1 operation must be encapsulated.
G34. the function should be at only one abstract level.
Encapsulate code that is not at an abstract level, so that each function is at only one abstract level.
G35. place configurable data at a higher level
Place the configuration data and constants in the base class.
G36. avoid passing browsing
Write shy code to let the collaborators provide the services they need, instead of visiting the entire system.
JAVA
J1. avoid too long import list using wildcards J2. do not inherit constants J3. constant VS. Enumeration
Use enum to replace constants.
Name
N1. use descriptive name
The name has a 90% readability effect and must be named carefully.
N2. The name should be consistent with the abstract level
Do not use the name of the Communication implementation: take the name of the reflection class or function abstraction level.
N3. use the standard naming method N4. unambiguous names as much as possible
N5. select a long name for a large range of functions N6. avoid Encoding
The name should not contain information of the type or range, such as m _, f, and other prefixes.
N7. the name should indicate the side effects
The name should indicate all information about the class, variable, or function, and do not hide the side effects.






Test T1. test Insufficiency
Ensure sufficient testing.
T2. use coverage Tool
The coverage tool can better find modules, classes, and functions that are insufficient for testing.
T3. skip small test
T4. ignored tests are questions about uncertain things.
Use @ Ignore to express our questions about requirements.
T5. test Boundary Conditions
Boundary interpretation errors are common and boundary conditions must be tested.
T6. comprehensive testing of similar defects
Defects tend to get stuck. If a defect is found in the function, the function is fully tested.
T7. the test failure mode is enlightening.
You can find the problem through test failure.
T8. the test coverage mode is enlightening.
Through the test coverage rate check, you can often find the test failure clue.
T9. test should be fast
Slow testing will lead to skipping when the time is tight, and may cause problems.


How to clean code

Sometimes writing code is like organizing and drawing architectural drawings. Without a clear idea and architecture, it is necessary to create a messy community, let alone a tall building. After reading this book, we feel that we need to take a good look at our previous code and ways of thinking. Coding. To be honest, it is a technical activity and a pipeline work. The key lies in how much effort is spent on it. Reading one should give you some insights.

Error Message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.