"Reading Notes"--the way of code cleanliness

Source: Internet
Author: User
Tags define exception repetition

"The attention to detail is even a more critical professional basis for any grand vision. First, developers get the skills and credit available for large-scale practices through small practices. Second, the smallest part of a magnificent building, such as a closed door, a little flattened floor, or even a messy desktop, will destroy the overall charm of the overall situation. This is what neat code is all about. "----is no better than the words in the book to explain the meaning of this book.

"Code Clean Road" is the 1th book Mountain has a road activity selected reader. Rather than remembering the rules of how to write neat code, it is more important to develop habits and ideas that keep your code clean and improve your code quality. The book is broadly divided into three parts, the first part of 1-10 chapters are introduced such as functions, classes, naming, unit testing, etc. to keep neat recommendations. The second part of Chapter 11-13 advocates the use of AOP, IOC, and other methods to maintain neatness, or, when appropriate, concurrent programming, from the aspect of system design. The third part, 14-17 chapters and later appendices, the author of the Java source code (the whole book is a Java example) to actually explain how to keep neat.

Later equals never

We have all had a glimpse of the mess we had created, and decided to abandon it and go on to a new day. We've all seen our rotten program run, and then assert that we can run a rotten program better than nothing, we have said one day and then back to clean up. Of course, in those days. We have not heard the brown rule: Later equals never later equals never.

PS: It's a bit of a shame to see this sentence. The deepest impression is that we went to see our own code a couple of years ago. That's what you write, it's really not going to go down. To make me change, I'd rather have one. So it's important to keep good habits at all times. Don't try to solve it later. Just like the leader said, this thing will be considered later, then there is no then.

Chapter One neat code

What is a neat code? Bjarne Stroustrup (c + + inventor) said: "I like the elegant and efficient code, the code logic should be directly, called the flaw is difficult to hide, minimize the dependency, make it easy to maintain, according to some kind of hierarchical strategy to improve the error handling code, performance tuning to the best, Instead of luring others into making unnecessary optimizations, get a bunch of clutter and neat code to do one thing.  "Ron Jeffries's understanding of the neat code: 1. Can pass all the tests.  2. There is no duplicate code.  3. Embody all the design concepts in the system. 4. Include as few entities as possible, such as classes, methods, functions, etc. In the above items, I am most concerned with code duplication. If a piece of code recurs, it means that an idea is not getting a good withdrawal in the code. I will try to find out what it is, and then try to express it in a clearer way. PS: Summary is the neat code 1. Clear responsibilities, no excess, 2. Reduce reliance and ease of maintenance. 3. Efficient. The second chapter has a meaningful name of 1. Truly. It's easy to say. Choosing a good name takes time, but it saves more time than it takes. Pay attention to naming, and once you have a good name, replace the old one.
int D; // the time to disappear, to the day count.  int elapsedtimeindays;

Ps:ctrl+r+r is a good use. The actual situation is more complicated than I post. We define different variables, we can see the name to know what it means, this is the most basic requirements.

2. Avoid misleading. For example, not a list type, do not use a accountlist to name, this is misleading.

3. Make a deliberate distinction.
Static void copychars (char a1[],char  a2[]) {for (int i=0;i< a1.length;i++) {
A2[i]=a1[i];}}

If the parameter names are changed to source and destination, the function will be much more presentable. Nonsense is redundant, the word variable should never appear in the variable name. The Word table should never appear in the table name. Namestring will be better than name, is the name a floating point? If there is a customer class, there is another class of Customerobject. is not messy.

4. Use a name that is easy to search

A single letter or numeric constant is difficult to find in a large pile of articles. Like the letter E, it is the most commonly used letter in English. Long places of interest in the short name, search for the name is better than the name of the self-compiled. A single-letter name is used only for local variables in short methods. The length of the name should correspond to its scope size.

5. The class name should be a noun or phrase, like customer,account, and avoid using a class name such as Manager,processor,data or info. The class name should not be a verb. The method name should be a verb or verb phrase, such as postpayment, Deletepage, or save, property access, modifications, and assertions should be named according to their values, plus get,set,is these prefixes. 6. Don't be cute, play with treasure, like who knows what the Holyhandgrenada function is, yes, it's a smart name, but DeleteItems may be a better name. 7. Each concept corresponds to one word.   and consistent. There are controllers and manager,driver in a bunch of code. will be confusing. For example, what is the essential difference between DeviceManager and Protal-controller? Chapter three functions 1. The first rule of the function is to be short, and the second rule is to be shorter. 2. The function should do one thing. Do it well. Only do this thing. 3. As few function parameters as possible. A function with two parameters is more difficult to understand than a unary function. If you need three or more than three parameters should be encapsulated into a class. 4. Don't repeat yourself. PS: If the same code appears two times, do you feel you have to do something about it. The proper use of the comments in the fourth chapter is to compensate for the failure we encountered when expressing our intentions in code. The author argues that annotations are a failure, and we can't always find a way to express ourselves without commenting, so there's always a comment, and it's not worth celebrating. One of the common motivations for writing comments is the existence of bad code.neat and expressive code with a small amount of annotations is more presentable than a fragmented and complex code with a lot of annotations。 Instead of spending time explaining the bad code comments you've made, take the time to clean up the heap of bad code. PS: This passage may seem a bit drastic. We can really reduce unnecessary annotations with good coding habits. However, the technique of automatically generating documents is now extracted from the comments in the code. If this is the case, the boss must be asking you to write a complete note. Good note: 1. Legal information. Sometimes, the company code specification requires the writing of notes related to the law. such as copyrights and works declarations. 2. Provide comments on the information.
// Returen An instance of the Responder being tested protected Abstract Responder responderinstance ();

However, the author argues that renaming a function name to a responderbeingtested comment is superfluous.

3. Interpretation of the intention. Sometimes annotations provide not only useful information about the implementation, but also the intent behind a decision. 4. Interpretation. Sometimes annotations translate the meaning of some obscure parameter or return value into a readable form. will also be useful. Especially if the parameter or return value is part of a standard library, or you cannot modify the code, the code that helps illustrate its meaning can be useful, for example:
Asserttrue (Bb.compareto (BA) = =1); // bb>aaasserttrue (A.compareto (b) ==-1); // a<b

It may not be clear how to look directly, but there are many notes. I think this 2,3,4 is a meaning. That's what that means.

5. Warning, tell others to pay attention to this method or the like.

6. Zoom in. Some of the code might look a bit redundant, but the coder had his own considerations at the time, and it was important to comment on this code. Avoid being optimized later.

Fifth Chapter Format

Portrait format: 1. Empty lines between functions and functions. 2. Variable declaration: The variable declaration should be as close as possible to its use position. Because the function is short, local variables should appear at the top of the function. 3. Entity variables should be included in the top, equivalent to our field fields, will be used more. 4. Correlation function, if one function calls another, they should be put together, and the caller should be placed on top of the callee as much as possible. This way the program will be naturally ordered. (I like to put the private method together before.) Of course it doesn't really make sense) 5. " The code for related concepts is put together. The stronger the correlation, such as a large functional logic. (more often I like to use the region to collect.) ) Landscape Format:

1. The length of the line, the author suggests that the upper limit is 120 characters

PS usually we are in accordance with their own screen size to decide, of course, too long, they are also inconvenient to read, not compressed JS file

2. Both ends of the assignment statement are left blank.
3. Do not add spaces between the function name and the opening parenthesis. Because the function is closely related to its parameters. 4. Indent. The source file is an inheritance structure, not an outline structure, and each level in the inheritance structure is tagged with a scope, that is, a block of code, with declaration statements and execution statements. To embody this inheritance structure, the source code should be indented. But sometimes we will write an if statement, while loop, or small function as a line, but there is no hierarchy concept, inconvenient to read, or indentation good.

Sixth chapter objects and data structures

1. Procedural code (function programming) facilitates the addition of new functions without altering the existing data structures, and the object-oriented code facilitates the addition of new classes without altering the existing functions. In turn, the code is difficult to add new data structures because all functions must be modified, and object-oriented code is difficult to add new functions because all classes must be modified. So in the design time to analyze whether to add a new function or to add a new data structure.

2. The Law of Delphi: The module should not be aware of the internal circumstances of the object it is manipulating. For example, method F of C can only invoke methods of the following objects.

    • C
    • Objects created by F
    • The object passed as a parameter to F
    • Variables held by the entity variables of C
var outpath=cxt.getoptions (). Getscart (). GetAbsolutePath ();

This code violates the above de-inked law and invokes the method of returning the value. This exposes the internal structure.

Seventh Chapter exception Handling

The 1.try code is like a transaction, and the catch Code block maintains the program in a persistent state. When writing code that might throw an exception, it is best to write the try-catch-finally statement first.

2. Define the exception class as needed. There are several ways to classify errors, depending on the source, whether it is a component or somewhere else, or depending on the type, whether it is a device error or a network error. But when we define exception classes, the most important consideration is how to capture them.

3. Do not return a null value. The code that detects null values is constantly seen in the program, and a missed detection can get out of control. Returns NULL, which the author thinks is a bad code. It is recommended that you throw an exception or return a specific object (the default value). Find the problem earlier. Similarly, you should avoid passing null values to other methods.

PS: In most programming languages, there is no good way to deal with null values that were accidentally passed in by the caller. We release the product should have a fault-tolerant mechanism, the program can not be easily collapsed, there should be a timely recording of anomalies or hints.

Eighth chapter boundary

Sometimes when we use third-party packages or open source code, or rely on the code of other teams in our company, we have to integrate neatly into our own code. This chapter describes the practices and techniques that keep the software boundaries clean and tidy.

1. For a third party to conduct a learning test, when a third-party package releases a new version, we can allow the learning test to see if the behavior of the package has changed.

2. Using code that does not yet exist, sometimes our third party has not developed the API, but does not affect the progress of our development, so we can first define the interface we want. If the third party is OK, we'll butt up again. 3. Manage third-party boundaries through interfaces, you can use the adapter mode to convert my interface to a third-party provided interface. This is to note that the third-party code and its own code mix too much to manage this inconvenience. Nineth Unit Testing Agile and TDD campaigns have encouraged many programmers to write automated unit tests that ensure that every nook and cranny in the code works as we wish. Three Laws of TDD
    1. Unless this allows failed unit tests to pass, no production code is allowed to be written.
    2. Only unit tests that can cause failure are allowed to be written. (compilation failure also belongs to a failure)
    3. Only write product code that is capable of causing a failed unit test to pass.
PS: What is the production code, here is a bit confusing. The test code is as important as the production code, it is not a second-class citizen, it needs to be thought, designed, and cared for in the north. It should be as neat as the production code. Unit tests make your code extensible, maintainable, and reusable. The reason is very simple, with the test, you do not worry about the code changes, no unit testing, each modification may lead to defects, a test, an assertion. A test that corresponds to a concept. We don't want extra-long test functions. The test should also comply with the following 5 rules. 1. Quick test should be able to run quickly, too slow you will not run frequently, will not find the problem as early as possible. 2. Independence. Tests should be independent of each other, and a test should not set conditions for the next test. When testing is interdependent, one fails to cause a series of tests to fail, making the problem diagnosis difficult. 3. Repeatable. The test should be repeated in any environment. 4. Self-sufficiency verification test should have Boolean output, regardless of pass or fail, should not be the view log file to confirm 5. Timely. Unit tests should be written exactly before the production code that makes them pass. PS does not know the actual development, the various companies are how to request. Team development will require unit testing, personal development I almost did not write unit tests. Tenth. Class 1. The class should be short 2. The single principle of responsibility (SRP): A class or module should have only one reason for modification. The system should consist of many short classes rather than huge classes. PS: Every system that reaches a certain size will include a lot of logic and complexity. The primary goal in managing this complexity is to organize it so that developers can find things, and conversely,systems that have huge, multi-purpose classes always make it difficult for us to trek through a lot of things we don't need to know now .。  3. Cohesion: If each variable in a class is used by each method, the class has the greatest cohesion. Cohesion is high, meaning that the methods and variables in the class depend on each other and combine them into a logical whole.  4. Organization for modification. Open closure principle (OCP): Classes should be open to extensions and closed to modifications. We can use interfaces and abstract classes to isolate the effects of these details.   11th: System   Separates the construction and use of the system: construction and use are different processes.  ps: When a building was built, the cranes and lifts were outside, and the workers were busy wearing safety clothes. When the building was completed, the buildings became neat and covered with glass walls and beautiful lacquer colors. The people who work in it, read a completely different picture. The same is true of software, which separates the areas of concern.  1. Factory, sometimes applications need to determine when to create objects, we can use abstract Factory mode. Isolate the details of the construction from the application.  2. Dependency Injection (DI/IOC). In a dependency management scenario, an object should not be responsible for instantiating its own dependency, but instead, it should transfer this responsibility to other rights-based mechanisms in order to achieve a reversal of control. PS now the dependency injection components are more, autofac,ninject and so on.  3. Expansion: "The right system at the outset" is purely a myth, whereas we should only achieve the needs of today's users. Then restructure, and tomorrow to expand the system, to realize the needs of new users. This is where the essence of iteration and incremental agility lies.   is like a city that has been demolished and built again.  4. Programming for Facets. In AOP, a module construct called facet (aspect) indicates which points in the system are modified in a consistent manner to support a particular scenario. This description is implemented with some kind of concise declaration (Attribute) or programming mechanism. Ps:mvc's filter is a good AOP, which can be programmed by the cross-sections of the test, from the permission validation, before the method enters, after the method enters, and before the result is returned. Better organization of code. Tenth, Chapter 11 is about a small part of the design. More likely to refer to books that specialize in design patterns.    12th Chapter  1. Simple Design Rule 1: Run all tests. Tightly coupled code is difficult to write tests. The more you write tests, the more you will follow the principles of dip, and use dependency injection, interfaces and abstractions to minimize coupling. As a result, there will be considerable progress in design. By following clear rules for writing tests and running tests continuously, the system will be closer to OO low-coupling, high cohesion goals. 2. Simple design Rules 2 refactoring:  in the process of refactoring, you can apply all the knowledge about excellent software design, improve the internalTo reduce the degree of coupling. In other words: eliminate repetition, guarantee expression, and reduce the number of classes and methods as much as possible. 3. Do not repeat. Repetition is the enemy of a good design system. It represents additional work, additional risk, and additional unnecessary complexity. There are multiple manifestations of repetition. A similar line of code is one. Other examples are:
int size (); bool isEmpty ();

These two methods can be implemented separately, but you can use size in IsEmpty to eliminate duplicates.

BOOLreturn size () = =0;}

Not only from the point of view of the line of code, but also from the function to eliminate duplication.

The 13th chapter: Concurrent Programming

Concurrency is a decoupling strategy that helps us break down what we do (the purpose) and when (timing). In a single-threaded application, the purpose is tightly coupled to the timing, and many times the state of the application can be determined by simply looking at the stack trace. The decoupling purpose and timing can obviously improve the throughput and structure of the application. From a structural point of view, an application looks more like a computer that works together, rather than a large loop. A single threaded thread spends many hours waiting for the end of the web socket I/O.

    • Concurrency adds some overhead to performance and writing extra code.
    • Correct concurrency is complex, even for simple problems.
    • Concurrency defects are not always reproduced, so they are often overlooked as accidental events and are not treated as true flaws.
    • Concurrency often requires fundamental changes to the design strategy.

Some basic definitions:

Several execution models are used in concurrent programming.

1) Producer-consumer model one or more producer threads create some work and place it in a cache or queue. One or more consumer threads get from the queue and do the work. The queue between producers and consumers is a qualified resource.     2) reader-author model. Throughput can be a problem when there is a shared resource that provides a source of information primarily for the reader thread but is only occasionally updated by the author thread. Increased throughput can lead to the accumulation of thread starvation and outdated information. Coordinating the reader thread does not read the information being updated, while the author thread tends to lock the reader thread for a long time.   3) Banquet philosophers. In many enterprise applications there is a situation where processes compete for resources, and without careful design, this competition is subject to deadlock, live lock, throughput and inefficiency.  PS: Here on the concurrency of the explanation is not so clear, to master how to use the correct concurrency, I still need to look specifically at this aspect of the book. Summary: Book 13 after the part is some Java source code optimization process of the explanation, I do not understand Java, here first skip. The most valuable part of this book is the habit of getting our programmers to have some neat code. From subtle variable commands, to functions, to the design of classes, and to the construction of the entire system. You cannot ignore each operation. Bad code is like a swamp, and it gets deeper and harder to change, so we're going to write neat code from the start. And as for design patterns or concurrent programming, from other booksLearningmore comprehensive. This book is not enough for our needs. PS: The book Mountain has the road activity is the reading group's friend together selected to read together a book. The code of cleanliness is the first issue. I am a scholar and this book has been read for seven days. About one hours a day. But today I take notes, basically the book is over again. The contents of the notes are based on my own judgment. If you want to get a thorough understanding, please read the original book. We are reading the second edition of the book is "Out of control", welcome interested friends to join. QQ Group 452450927

"Reading Notes"--the way of code cleanliness

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.