четверг, 7 января 2016 г.

15 rules of writing quality code


There are millions of ways to write bad code. Fortunately, to rise to the level of quality code, just follow the 15 rules. Their observance will not make you the master, but will allow convincingly simulate it.
● Rule 1: Follow the programming style.
Every programming language has its own programming style that tells how to indent, where to put the spaces and brackets as name objects, how to comment code etc.
For example, this piece of code in accordance with the standard error have 12:
for (i = 0; i <10; i ++) {
Study the standard of care, learn the basics by heart, follow the rules as the commandments, and your program will be better than most written graduates.
Many organizations will adapt standards to suit your specific needs. For example, Google has developed standards for more than 12 programming languages. They are well thought out, so read them, if you need help in programming at Google. Standards even include configuration editor that will help you to comply with the style and special tools, your code is verified for compliance with this style. Use them.
● Rule 2: Let's descriptive names.
Restricted slow, clumsy teletypes, programmers used in antiquity contracts for variable names and procedures to save time, knocking on the keys, ink and paper. This culture is present in some communities for the sake of backward compatibility. Take, for example, break the language function C wcscspn (wide character string complement span). But this approach is not applicable in the present code.
Use long descriptive names like complementSpanLength, to help themselves and colleagues to understand your code in the future. Exceptions are a few important variables used in the method body, such as iterators cycles, parameters, time values, or the results of execution.
More importantly, you have to think long and hard before something called. Is the exact name? Did you due highestPrice instead bestPrice? Is there enough specific name in order to avoid its use in other contexts for similar within the meaning of the objects? Is not it better to call a method getBestPrice instead getBest? Is it better than other similar names? If you have a method ReadEventLog, you should not call other NetErrorLogRead. If you call the function, whether its name describes the return value?
In conclusion, a few simple rules for naming. Class names and types must be nouns. The name of the method should contain a verb. If the method determines whether any information about the object is true or false, the name must begin with «is». Methods that return the properties of objects, must begin with «get», and set property values ​​- «set».
● Rule 3. Comment and document.
Start each method and the procedure described in the comments that the method or process does, parameters, return values ​​and possible errors and exceptions. Describe the role of each in the comments of the file and the class content of each class of the field, and the basic steps of a complex code. Write comments as code development. If you believe that then write them, you are cheating yourself.
In addition, make sure that your application or library, there is a guide that explains what your code does, determines its dependencies and provides instructions for assembling, testing, installation and use. The document must be short and easy; a README-file often enough.
● Rule 4: Do not repeat.
Never copy and paste code. Instead, select a common part to a method or a class (or a macro, if necessary), and use it with the appropriate parameters. Avoid using these and similar pieces of code. Also, use the following techniques:
Creating API reference of the comments using Javadoc and Doxygen.
Automatic generation of test Unit-based annotations and naming conventions.
Generate PDF and HTML markup from one source.
Getting the class structure of the database (or vice versa).
● Rule 5. Check for errors and respond to them.
Methods can return the signs of bugs or throw exceptions. Treat them. Do not rely on the fact that the drive is never full, your configuration file will always be in place, your application will run with all the necessary rights, requests for memory allocation will always be successfully fulfilled, or that the connection is never cut short. My Computer - Best Public! Yes, a good error handling difficult to write, and it makes the code is longer and harder to read. But ignoring the errors just sweeps the problem under the carpet, where the unsuspecting user once it detects.
● Rule 6. Separate the code into short, separate parts.
Each method, function, or code block must fit in the normal display window (lines 25-50). If you get a long, divide into smaller pieces. Even within the method of separating the long code blocks, the essence of which can be described in the comment at the beginning of each block.
Moreover, each class, module, file, or process should perform a certain kind of tasks. If a piece of code performs a completely diverse tasks, then divide it accordingly.
● Rule 7 uses an API frameworks and third-party libraries.
Learn what features are available using the API of your framework. and that they can do advanced third-party libraries. If libraries are supported by your system package manager, they are likely to be a good choice. Use the code that holds the desire to reinvent the wheel (though useless square shape).
● Rule 8. Do not go overboard with the design.
Design only what matters now. Your code can be done quite generalized, that it supports the further development, but only if it does not become too complicated. Do not create parameterized classes, factories, deep hierarchies and hidden interfaces to solve problems that did not exist - you can not guess what will happen tomorrow. On the other hand, when the structure of the code does not fit the problem, do not hesitate to refactor it.
● Rule 9. Be consistent.
Do the same thing in the same way. If you develop a method which is similar to the functionality of existing functionality, use a similar name, like the order parameters and a similar body structure. The same applies to classes. Create similar fields and methods, make them similar interfaces, and compares the new names already exist in similar classes.
Your code must match your framework agreements. For example, it is good practice to make half-open ranges: closed (including) to the left (at the beginning of the range) and open (exclusive) to the right (at the end). If a specific case there is no agreement, then make a choice and stick to it fanatically.
● Rule 10. Avoid security issues.
Modern code rarely works in isolation. It is an inevitable risk of becoming the target of attacks. They do not necessarily have to come from the Internet; attack can occur through the input of your application. Depending on your programming language and subject area, you may want to worry about buffer overflows, cross-site scripts, SQL-injections and other similar problems. Read these problems and avoid them in the code. It is not difficult.
● Rule 11. Use efficient data structures and algorithms.
Simple code is often easier to maintain than the same, but modified for the sake of efficiency. Fortunately, you can combine the maintainability and efficiency, using data structures and algorithms that enables your framework. Use the map, set, vector and algorithms that work with them. In this way your code will be cleaner, faster, more scalable and more economical memory. For example, if you save thousands of values ​​in a sorted set, then the intersection operation will find elements in common with the other set for the same number of operations, and not for a million comparisons.
● Rule 12. Use Unit-tests.
The complexity of modern software makes installation more expensive and more difficult to test. Productive approach would be to support every piece of code tests that verify the correctness of his work. This approach simplifies debugging because it allows you to detect errors earlier. Unit-testing is necessary when you are programming in dynamically typed languages ​​like Python and JavaScript, because they catch any errors only at the stage of execution, whereas statically typed languages ​​such as Java, C #, and C ++ can catch some of them in compile time. Unit-testing also allows you to refactor the code with confidence. You can use XUnit to simplify writing tests and automate their start.
● Rule 13. Keep the code portable.
If you have no particular reason, do not use the functionality that is available only on a specific platform. Do not rely on the fact that certain data types (such as integer, indexes and timestamp) will have a particular length (eg, 32 bits), because this parameter is different on different platforms. Keep the messages of the program separately from the code, and to sew up the parameters corresponding to the particular culture (eg, fractional dividers and the whole or part of the date format). Agreement need to code can be run in different countries, so do the localization as painless as possible.
● Rule 14. Make your code going.
Simple team must collect your code into a form that is ready for distribution. The team should allow you to quickly assemble and run the necessary tests. To achieve this, use the automated build tools such as Make, Apache Maven, and Ant. Ideally, you should set an integration system that will scan, collect and test your code with any change.
● Rule 15. Place everything in the version control system.
All of your items - code, documentation, source code tools, build scripts, test data - should be in the version control system. Git and GitHub make this task a cheap and hassle-free. But you are also available, and many other powerful tools and services. You should be able to assemble and test your program on the configured system, just download it from the repository.
Conclusion.
With these 15 rules a part of your daily practice, you will eventually create code that is easier to read, which is well-tested, are more likely to start up correctly, and that it will be much easier to change when the time comes. You also will protect yourself and your users from a large number of headaches.

Комментариев нет:

Отправить комментарий