< reading notes > code neat Way

Source: Internet
Author: User

Overview1, the content of this document is mainly from the book "Code Clean Road" author Robert C.martin, belongs to reading notes. 2, software quality, not only depends on the architecture and project management, but also closely related to the code quality, this book proposes a code quality and cleanliness in direct proportion to the point of view, and gives a series of effective clean code operation practices, as long as follow these rules, you can write clean code, thereby improving the code quality. 3, the book introduces the rules are from the author's many years of practical experience, covering from naming to refactoring of multiple programming aspects, has a good learning and reference value. 4, workhouse to have two: know and line. You should learn about the rules, patterns, and practices, exhaust what you should know, and be knowledgeable about it, and master it through hard practice! PrefaceIt's hard to learn a neat code, it's more than asking you to master principles and patterns, and you have to work on it and practice it yourself and experience failure. You must observe how others practice and fail, how to walk, and then turn around to learn their ways. This book asks you to use more information, work harder, and be very diligent. How to work hard? -Read the code a lot and wonder where the code is and where it's bad. This book is roughly divided into three parts: principles, patterns and practices.

First, the use of meaningful naming

1. A veritablePay attention to naming, once found a better name to replace the old, so that people will be more happy to read the name itself should be able to explain its meaning, without comments to understand is the best. such as int d;//vanishing time, to the day int elapsedtimeindays, the former name does not have any meaning, in the application of the program can not see the actual role of the variable, need to correspond to the comments to understand, so far less than the latter name good! 2. Avoid misleadingProgrammers must avoid leaving behind false clues that hide the code's meaning and avoid using words that contradict their intentions. Beware of the differences in the use of details the same spelling, inconsistent spelling (case difference), is misleading. When you use the editor name auto-complete function, a variable with similar spelling can cause a false selection. Avoid using lowercase l and capital letter O as variable names, easily confused with 1 and 0 3. Make a meaningful distinctionAvoid naming with a digital family, which does not provide the right information and clues to the author's intentions. Do not use similar names, such as ProductInfo and productdata variables, meaning, it is easy to confuse the meaning of confusion do not use redundant information, such as Namestring, is the name a floating point? If so, it should not be named with name. 4, using the name of the read outHuman is good at remembering and using words, if the name can not read or pronunciation, it is not a good name, discussion and communication is difficult to express. For example, the function name is: GENYMDHMS ()//generation date, Month day seconds. Do not use silly self-made words, but use proper English words. 5. Use searchable namessuch as the letter e,f and so on is not a good variable name, it is commonly used letters in English, inconvenient to search, single-letter name is limited to local variables used, the name should be relative to the scope size if the program uses the same number, the same function, you need to use macro-defined variables instead. For example, Work_days_per_week is better than the number 5 search, but also more to reflect the author's intentions 6. Avoid using codingNo need to type and scope into the name, this will only trouble, not only inconvenience pronunciation, but also easy to misspell, to solve the problem is not helpful. The Hungarian notation, which destroys the rules of non-coding, should not be used. You do not have to use a member prefix, you should make the classes and functions small enough, and use an editing environment that can highlight and color the members. (keil,notepad++ is supported). 7. Avoid thinking mapReaders should not be allowed to translate the names in your brain into their well-known names, a question that is common in choosing the terminology used in the problem area or in the solution domain. When you are a local variable and the name does not conflict, you can use I,j,k as the loop variable. Professional programmers use their ability to write code that is understandable to others 8. Class nameThe class name should be a name or a noun phrase, such as a customer, account, and avoid using the class name manager, Data, info, which should not be a verb.

9. Method name

The method name should be a verb or a verb phrase, such as postpayment, Deletepage, or s**e, and the property access should be prefixed with a set, get, is prefix 10. Each concept corresponds to a wordChoose a word for each abstract concept, and consistent. For example, the use of fetch, retrieve, get in multiple classes in the same way named, it is easy to cause confusion. 11. Don't use punsAvoid using this for different purposes, and the same term for different concepts is puns. For example, there are add methods in more than one class, this method obtains the new value by adding or linking two existing values, if a new class means putting a single parameter into the Cluster (collection), using the Add name, while keeping the name consistent, you have a different meaning, you should use INSERT. 12. Use the name of the solution domainBecause only programmers will read your code, the name should choose the name of the solution realm, not the name of the problem design realm. For example, name Accountvisitor is more meaningful than jobqueue. 13. Use the name originating from the problem area involvedWhen naming a term that is familiar to programmers, it is appropriate to use code that is more closely related to the domain of the problem in question, and should take the name from the problem domain 14. Add a meaningful contextFew names can be self-explanatory-most do not, so it is necessary to use well-named classes and functions to place names and provide context to the reader. For example, adding prefixes Addrfirstname, addrlastname, addrstate, can provide context, these variables belong to the address range. It's a better practice to create a class called address that holds these related variables. The enhancement of context also allows the algorithm to become cleaner by decomposing into smaller functions. 15. Do not add meaningless contextsFor example, the application (gas station Deluxe) is referred to as GSD, so adding the same prefix for each function, class, variable is not a good idea to name the GSD. Address is a good name, but if you need to differentiate it from a MAC address, port address, or Web address, you should use PostalAddress, Mac, and URI to make the name more accurate. 16. SummaryThe hardest part of naming a word is the need for good descriptive skills and a common cultural background try the above rules to see if your code is more readable. If you maintain someone else's code and use refactoring tools to solve the problem, the effect will be immediate and sustainable. Ii. Some rules about functions 1. ShortThe first rule of a function is short. The code length is capped at 20 lines for best. The block of code for the If,else,while statement should be only one line, which will not only keep the function short, but also increase readability. The hierarchy of functions should not be more than two layers, so it is easy to understand and read. 2. Do only one thingThe function should do only one thing, do this thing well. The way to judge whether a function only does one thing is to see if it can break out a function, which is not simply a reinterpretation of its implementation. 3. An abstraction level for each functionTo make sure that the function does one thing, the statements in the function are at the same level of abstraction. This is the key to keeping the function short. 4. Function ParametersPreferably less than 3, 0 and 1 best, 3 or more please use a struct instead. Output parameters are more difficult to understand than input parameters, and when reading a function, it is customary to think that the information is output through the parameter input function through the return value. Give the function a good name so that it can explain the intent of the function well and the order of the parameters. For example Assertexpectedequalsactual (expected,actual) is easy to understand and remember. 5. No side effectsSide effects are things that are hidden by them, such as the power-on check password function, if the password is not initialized before the call, it will make an error, hiding its timing coupling requirements. The ability to initialize the password should be added to its function, although it violates only one thing. 6. Split instruction and queryA function that modifies the state of an object or gets the parameters of the object should be divided into two function implementations.    For example, if the function sets a specified property, if success returns TRUE, the failure returns false, the use case is as follows: if (Set ("username", "unclebob") ... Such statements understand that there is ambiguity, set is a verb, but in the context of feeling like an adjective, from the reader's point of view, this sentence means to ask whether the property of username is set to Unclebob, or whether the property of username is successfully set to Unclebob?  It is therefore advisable to change to the following: if (attributeexists ("username")) {SetAttribute ("username", "unclebob"); } 7. Use exceptions instead of return error valuesThe direct return error code encourages the use of directives as expressions in an if statement, resulting in multiple levels of nested structures. If an exception is returned in place of the error code, the error-handling code can be separated from the main path code and be simplified 8. Do not repeatDuplicate code maintainability is poor, if the algorithm changes, the areas involved are to be updated, the code is bloated, but also increase the likelihood of error! If an algorithm repeats itself in a different function, it needs to be repaired with a separate function. Object-oriented and component-oriented programming is more or less a strategy to eliminate duplication. 9. Structured ProgrammingAs long as the function is short, the occasional return, break, continue statement has no disadvantage, even more expressive than single-entry single-out. Goto statements can only be used in large functions, so avoid them as much as possible. 10, how to write a short functionWrite the code and write the article, write a first draft, and then polished, until you reach the look of the heart. The first-written functions, which are usually lengthy and complex, have too many indentation and nested loops, have a random name, and the code repeats. You can write short refining functions by decomposing functions, modifying names, eliminating duplicates, and then following the rules of this chapter and re-assembling functions. three rules about annotations 1, comments can not beautify the bad codeNeat and expressive code with a small amount of annotations is much more presentable than fragmented and complex code with a lot of annotations! Instead of taking the time to write notes, take the time to clean up the bad code early. The code is changing, evolving, and unfortunately, the comment is not always changed, and the longer it is, the longer the comment is intended to be from the code. Only the code is the only truly accurate source of information. 2. Use code to explainUse the code itself to explain its behavior. For example,//check to see if the employee are eligible for full benefits if (Employee.flags &hourly_flag) && (E            Mployee.age > 65)) by creating a function that says the same thing as the annotation. if (Employee.iseligibleforfullbenefits ()) 3, good commentLegal information, such as legal notes, copyright notices, etc. that are required by the company code specification. A better way to provide comments on information is to use a function name to convey information. Explanation of Intent: annotations provide not only useful information about the implementation, but also the intent behind a decision. Explanation: It is useful to translate obscure parameters or return values into a readable form of annotations. Caution: Annotations that are used to warn other programmers of some consequences are also useful. 4. Bad CommentsMumbling: Just feel as the process needs to add comments. Superfluous comment: It is not possible to provide more information in itself than the code is superfluous. Misleading comment: A comment that has an imprecise or misleading meaning. Compliance notes: The rule that every function or variable has to be annotated is completely ridiculous and only confuses the code. Log comment: In today's source control system, this lengthy record only makes the module messy and should remove the nonsense comment: chatter about the obvious, nothing new. People who look at the code are almost blind to it. So with the determination to tidy up the code to replace the impulse of nonsense, it will make you a better programmer. Horrible nonsense: In the j**adoc of the well-known open Source Library, you can also see the copy sticky error, meaning that the variables are different, the annotation is the same. Positional markers: Use less tag bars, such as//action//////////////////////////////, where specific functions are placed below, most of the time unnecessary. Comments after parentheses: Although for multi-layered nesting is helpful, but should use short, encapsulated function, if you want to mark the closing parenthesis, you should actually do is to shorten the function. Attribution and attribution: The source control system is very good at documenting who changed what, and there is no need to dirty code with a small signature. For example Comment/*added by rick*/commented out of code: directly to comment out the code is annoying practice, others may think that it must have a reason to stay here dare not Delete, the last commented out code like scum piled up there, do not do so! Comments that are too informative: don't add historical topics or irrelevant details to your comments. No obvious link: the role of annotations is to interpret code that is not self-explanatory, which is not necessary if you need to explain it yourself. Function Head: Short function does not need too many comments, just write a good name is much better than the comment! Four rules about code formattingYou should maintain a good code format, choose a set of simple rules to manage the code format, and then implement it. If you work in a team, the team should agree to adopt a simple set of formatting rules that all members must follow. Using automated tools that can help you apply these formatting rules can be helpful. 1, the purpose of the formatAfter the original code has been modified for a long time, its code style and readability still affect maintainability and extensibility. Code format is about communication, and communication is a top priority for professional developers! What code formats can help us communicate? 2. Vertical formatVertical dimensions The length size of a single file is related to the comprehensible, and statistics show that a single file with a majority of 200 rows to 500 lines can construct an excellent system, and short files are often easier to understand than long files! function layout function name should be enough to tell us whether in the correct module, the top of the source file should give a high-level concept and algorithm, the details should be expanded down to the lowest level of the source file functions and details. Just like the newspaper, the headline outlines the outline of the title, and the content unfolds in detail. Empty lines should be separated by a blank line between package declarations, functions, and blocks of code, a simple rule that greatly affects the visual appearance of the code. Blank lines, as a clue, mark the concept of independence. Near if a blank line separates the concept, the near code implies a close connection between them. So a close relationship should be close to each other. The vertical distance global variable declaration should be placed before the first function declaration of the file, and the local variable declaration is placed at the top of the function. The related functions should be put together, the caller is placed on the callee, so that the called function can be easily found, greatly enhancing the readability of the module 3. Horizontal FormatLine width How wide should one line of code be? Statistics show that 70% of the code line is less than 60 characters, the line should be as short as possible, stick to 80 bytes a bit rigid, but not more than 100 characters or 120 characters. The simple rule is that you can see all the code without dragging the scroll bar to the right. The horizontal area is separated from each other at both ends of the operation symbol (except multiplication sign, because it has a higher priority, most formatting tools ignore the priority), between the function name and the closing parenthesis, and a space is added between the functions arguments! Horizontal alignment experience indicates that variable names in a set of class declarations, or rvalue alignment of an assignment statement, have no practical effect, so the left side is aligned and the same space is used to differentiate the rules. Indenting a code structure with indentation, it's easy to find new declarations, variables, classes, and function blocks when reading, otherwise it will take a toss to understand that programmers should rely on indentation mode (forcing indentation in Python to represent the scope of a for loop, using curly braces in C, but also relying on indentation to enhance readability). Empty range Sometimes the statement body of the while or for statement is empty, as shown below. The semicolon at the right end is hard to see and confusing. while (Dis.read (buf,0,readbuffersize)! = 1), it is best to change to the following format while (Dis.read (buf,0,readbuffersize)! = 1) {} team rules in the team, Members should have a consistent code format that increases the complexity of the project code if their styles are different. Five Unit TestOver the past 10 years, the programming profession has progressed a lot, especially in agile and TDD (test-driven development) campaigns that have encouraged many programmers to write unit tests. TDD want us to write the test before writing the production code, and there are three laws: Law one: Before the test drive cannot be tested, you cannot write the law of Production Code two: only can write a unit test just can't pass, You cannot compile or pass the law three: you can only write production code that is just enough to pass the current failure test. These laws require the test to be written along with the production code, the test code is written first, so the program is written, and the test overwrites all production code. 1, keep the test cleanThe test code, like the production code, needs to be thought, designed, and cared for, as neat as the production code is, unit testing makes your code extensible, maintainable, and reusable. Without testing, every modification can be flawed, no matter how extensible the architecture is, how well the design is partitioned, and if no unit tests are available, your changes can lead to unpredictable flaws. 2. Neat TestThe only element of neatness is readability, which is more important in unit tests than in production code. How is readability done? is to be clear, concise and have enough expressive power. Test to use the construction-operation-Test mode, each test should be clearly divided into three links, the first link to construct the test data, the second link operation test data, the third link to check whether the operation has the desired results. 3. One assertion per testA single test function has and only one assertion is a good rule. Each test does a concept test, and if a test measures three things, it may lead to omission. 4. Neat 5 RulesFast, the test should run quickly so that you can run it frequently, and if you don't run it frequently, you won't be able to spot problems early. Independent (independent), testing should be independent of each other so that each test can be run separately. Repeatable (repeatable), the test should be repeated in any environment, or you will not be able to run the test if the current environment is available. Self-sufficiency verification (self-validating), the test should have a Boolean output to go, in any case should not look at the log file to confirm whether the test passed. Timely (timely), testing should be written in a timely manner, if you write the test after the production code, you will find that the code is difficult to test.

< reading notes > code neat Way

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.