The way to clean code

Source: Internet
Author: User
Tags comments data structures exception handling functions repetition

Now the difficulty of software system development lies mainly in its complexity and scale, and customer demand is no longer like the Winston Royce waterfall model expected to complete all the design before the system code to meet user software requirements. In this era of rapid information explosion technology, demand is constantly changing, with the industry in 2001, 17 of Daniel gathered in the United States Utah State ski resort Snow Bird (snowbird) Snow field, put forward the "agile" (Agile) software development values, and in their efforts to promote, began to pop up in the industry. In the "Code neat" (clean code), a kind of software quality, sustainable development is not only the project architecture design, but also closely related to code quality, code cleanliness and quality directly proportional to the quality of a neat code is reliable, for team development, post maintenance, reconstruction has laid a good foundation. In this book, the author puts forward the details of the practical development practice, rather than standing in the empty theory to talk about the neat way.

What is neat code? Different people will stand in different ways to elaborate different statements. And my favorite is Grady Booch (the author of object-oriented analysis and design) states:

"Neat code is straightforward. Neat code is like a beautiful prose. Neat code never hides the designer's intent, full of neat abstractions and straightforward control statements. ”

Neat code is a minimalist (simple but not too simple) design, people who read the code can clearly understand what's going on here, not the obscure, the neat code that reads like a prose-art precipitate, and the author is careful to create it.

One: Naming

Naming includes variables, functions, parameters, classes, etc., a good name can be a good description of the business that it carries, from the name has been very good answer to why exist, what to do, how to use the majority of the problem, the reader can see it without going into the details of its implementation, everything in the name of a glance. A good name must be a veritable one, with no ambiguity (puns or common conflicts), straightforward (negative statements or misleading naming).

Two: Functions:

From the Assembly/C era to the present function has always existed with us in the development of an integral part of the structured organization, reuse. As a first-class citizen of functional language, the first set of code for all programs.

A good function must be small enough, followed by small enough. It's easy to imagine how great a psychological challenge it is to read thousands of lines of code, and to work in an internship without layered logic on a WinForm platform, relying entirely on the RAD model to bring back thousands of lines of code after the CS page, every modification annoyed me, and wanted to rewrite the entire business logic.

A function is short and short, only do one thing, and do a good job, only do one thing to get better using the function name to express themselves.

Good functions should also be CQS (Query command separation) without side effects (there is no hidden ambiguity behind the logic), and there is no other type of "attachment plot (Feature Envy)" (variables in the class are used by all functions this is ideal for high cohesion, all things have their place, and then the object to its place).

The parameters of the function should be less than the best, one at a time, two again, try to avoid three and more than three, and for too many parameters you might want to adopt introduceparameterobject (introducing the Parameter object).

Duplicate code. Repetition in software systems is all evil, we are familiar with the separation of concerns, object-oriented, design principles ... Are all meant to reduce repetition and improve reuse, Don ' t repeat yourself! (DRY).

Three: annotation, format:

Not writing a complete annotation is a good developer, and if the code clearly expresses its intent, then the annotations are superfluous. In refactoring-improving existing code, Martin Fowler points out that redundant annotations are a bad code taste. It's a good note. As the maintenance of the project is constantly being refactored, it will often become less adaptable, and we rarely take proactive maintenance. Moreover, misleading comments are more hated by the user. Of course, sometimes we have to use annotations, annotations are not all evil, when we can not use code to describe ourselves, we need to comment to describe the intent of the unnecessary side-effects of the code to provide users with warning comments. Todo development time control, such as you are in the larger area of refactoring, some of the current logic is no longer adapt, not so natural, and its refactoring is still in the task list at the end, you can choose to mark in the Todo, and finally finish removing every todo task from the todolist.

Good code format will make it easier for us to read, a common set of formats will let us find understanding faster. Each team should follow a fixed set of code format specifications, the entire software system unified style, rather than fragmented into one.

Four: Objects and data structures:

Data structure refers to the information of the carrier, exposing the data, and almost no meaningful behavior of the anemia class. The most common applications are in distributed services, the indispensable data transfer object (DTO) pattern in distributed services such as Wcf,webservice,reset, and the DTO (Request/response) is a very typical carrier, with only simple get, Set property and is more likely to exist as a value object. And the object is just the opposite. As an object-oriented product, it is necessary to encapsulate the hidden data and expose the behavioral interface, and DDD domain model tends to not only manipulate itself or associate state in the data more exposed behavior.

The slight difference between the data structure and the object is the difference between the two: the code that uses the data structure facilitates the addition of new behaviors (functions) without altering the current data structure, and the object-oriented code makes it easy to add new classes without altering existing functions. In other words, it's hard to add new data types to the structure, because you need to change all the functions, and object-oriented code is hard to add new functions because you need to modify all the classes. In any complex system where data structures and objects exist at the same time, we need to determine whether we need new data types or new behavior functions to add.

Hidden as the most important feature of object-oriented, encapsulation hidden is the most important feature of object-oriented, a good object-oriented code is definitely to the object's internal details to do a good hiding package, after encapsulation is polymorphic, delegation and so on. A good object-oriented code must be

With good hidden encapsulation, easy to test, unstable factors tend to be concentrated in a small or fixed position, the change of unstable factors will not lead to more extensive changes in the diffusion.

Hidden requirements for objects: methods should not operate with any object returned by the calling method, in other words, talk to friends, not talk to strangers (Dimitri Law, or translated into the minimum knowledge principle), such as: Ctxt.getoptions (). Getsearchdir (). GetAbsolutePath () is the inverse model of the Dimitri rule.

V: Exception Handling:

Every software system avoids exception handling and needs to be prevented from messing with our logic.

Using exception handling instead of returning an exception encoding, returning an exception encoding would be the code that is full of if/else,switch/case disturbing my code flow.

For a specific exception to catch, you can programming for the exception, write specific exception classes, so that the exception package conversion, more easily catch aftermath of treatment.

Avoid returning null, the most common headache in software systems is NullReferenceException. In a non specific scenario, we should try to avoid returning null. In the face of this scenario, we can return the null object pattern (the empty objects mode) to the exception object, such as Guid.empty,string.empty in the C # class library, and for the collection type we can return an empty set of length 0 rather than null;

VI: Borders:

In the system development can not all start from scratch, write all the code, the better solution is to integrate some open source or third-party projects, for my use. But you can't let these non-self code seep through our code, there are a number of powerful third-party products, but not necessarily a good abstraction. Many times I would rather take the time to abstract out the interfaces we need in the third party class library, and then layer our own abstraction, this not only facilitates TDD, because we are able to create pseudo objects so that the tests are independent of external resources, get fast feedback, and are well designed to scale, When for some reason, such as third-party libraries no longer meet business needs, or equity fees, etc., we can switch to the bottom of the well and make the changes will not spread to the system everywhere. The outer covering class is also a good practice for handling legacy code into test containers.

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.