Some principles of software design

Source: Internet
Author: User
Keywords We this is realize can

In the past, we have introduced some principles of software development, such as the 10 commandments of high quality code and the UNIX design principles described in the UNIX legend (next article). I believe that you can learn from middle school some knowledge of design principles, as I said in the "How Do I Recruit procedures", a good programmer usually consists of its operational skills, knowledge level, experience level and ability four aspects. Here I would like to talk about some of the principles of design, I think these things belong to the long-term experience summed up knowledge. These principles should be understood by every programmer. But please do not dogmatism, in the use of time or more to consider the actual situation. In fact, the following principles, not just software development, can be extended to other production activities, even our lives.

Don ' t Repeat yourself (DRY)

DRY is the simplest law and the easiest to understand. But it may also be the hardest to apply (because to do so, we need to make considerable effort in generic design, which is not an easy task). It means that when we find some similar code in two or more places, we need to abstract their commonalities to form a unique new method, and change the existing code to let them invoke the new method with some appropriate parameters.

Reference: Http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Keep It simple, Stupid (KISS)

The kiss principle may be most admired in design, at home design, interface design, operation design, the complexity of the more and more people are BS, and simple things are increasingly recognized, such as the design of these UI and our Chinese Web page (especially Sina's Web page) is a negative example. Ikea's simplicity, efficiency of home design, production ideas; "Microsoft" (Microsoft) "WYSIWYG" concept, "Google" (Google) simple, direct business style, without exception to follow the "kiss" principle, it is the "kiss" principle, These seemingly magical business classics. And Apple's iphone/ipad this principle to the extreme.

It's a simple thing to complicate a thing, but it's complicated to make a complicated work simple.

Reference: Http://en.wikipedia.org/wiki/KISS_principle

Program to a interface, not a implementation

This is the most fundamental philosophy in design patterns, focusing on interfaces, not implementations, dependencies, not implementations. Interfaces are abstract and stable, and implementations are varied. We will refer to our dependency inversion principle in the solid principle that we will object to later, which is another aspect of this principle. There is also a principle called composition over inheritance (like combination rather than inheritance), these two are the design principles of the 23 classic design patterns.

command-query Separation (CQS) – command-Query separation principle query: When a method returns a value to respond to a problem, it has the nature of the query; command: When a method changes the state of an object, it has the nature of the command;

Typically, a method may be pure command mode or pure query mode, or a mixture of both. When designing an interface, if possible, you should try to single the interface to ensure that the method behaves strictly as a command or as a query, so that the query method does not change the state of the object, there are no side effects, and the method that changes the state of the object cannot have a return value. In other words: if we ask a question, then it should not affect its answer. Practical application, depending on the situation, the clarity of semantics and the simplicity of use need to be weighed. Combining command and query functionality into one method facilitates the customer's use, but reduces clarity and may not facilitate the assertion based programming and requires a variable to hold the query results.

In the system design, many systems are also designed with this principle, the query function and command function of the system separation, which is in the system performance, but also conducive to the security of the system.

Reference: Http://en.wikipedia.org/wiki/Command-query_separation

you Ain ' t going Need It (YAGNI)

The principle is simply to consider and design the necessary functions to avoid excessive design. Just implement the functionality you currently need, and you can add it later when you need more functionality.

if unnecessary, do not add complexity. Software development is first a communication game.

There was an article on excessive refactoring in the previous site, and this example is a counter example of this principle. The designer of WebSphere said that he had designed the product over and over. When a programmer or architect designs a system, it takes a lot of extensibility into account, resulting in a great deal of compromise in architecture and design, which ultimately results in a project failure. This is an ironic lesson because it was hoped to prolong the life cycle of the project as much as possible, with the result shortening the life cycle.

Reference: Http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It

Law of demeter– Dimitri rule

The Dimitri rule (law of Demeter), also known as the "minimum knowledge principle" (principle of least knowledge), was derived from a project called Demeter at the University of Holland in 1987. Craig Larman called the Demeter "Don't Talk to strangers". The chapter on LOD in the "Programmer's Way of cultivation" is called the "solution coupling and Dimitri law". There are some very figurative metaphors about the Dimitri law:

If you want your dog to run, would you say to the dog or to the four-legged leg? If you go to the store to buy something, will you give it to the clerk, or will you give it to the clerk to get it?

Talking to the dog's limbs? Let the clerk get the money from his wallet? This may sound absurd, but it's almost as flattering in our code.

For LOD, the formal statement is as follows:

For a method ' m ' in the object ' O ', M should be able to access only the methods in the following objects:

object o; Component object directly related to O; objects created or instantiated by method m;

In the clean Code book, there is a section of the Apache framework that violates the LOD code:

Final String OutputDir = Ctxt.getoptions (). Getscratchdir (). GetAbsolutePath ();

Such a long string of details about other objects, details of detail, details of detail ... Calls, adding coupling makes the code structure complex, rigid, and difficult to extend and maintain.

In the book "Refactoring" The Code of the ring flavor is called "Feature Envy" (attachment complex), the image describes a violation of the LOC situation. Feature envy means that an object is more interested in the content of other objects, that is, it always admires the members, structures, or functions of other objects, and calls people all the way. Such a structure is obviously unreasonable. Our program should be more "shy". You can't just take a guest's wallet and take it out like the one in the previous example, who doesn't treat himself like an outsider. The "shy" program only talks to your nearest friend. In this case, the structure of the program should be adjusted to allow the object to own the feature it admires, or to use reasonable design patterns (such as facades and mediator).

Reference: Http://en.wikipedia.org/wiki/Principle_of_Least_Knowledge

Object-oriented S.O.L.I.D principle

This is generally a five-object design principle, but I think these principles apply to all software development.

Single responsibility Principle (SRP) – One principle of responsibility

With regard to the principle of sole responsibility, the core idea is that a class, doing only one thing and doing it well, has only a reason to cause it to change. The principle of single responsibility can be regarded as the extension of low coupling and cohesion in the object-oriented principle, defining responsibility as the cause of change, so as to increase cohesion to reduce the cause of change. The more responsibilities that may cause it to change, the more it will lead to duty dependency, which has an impact on each other, resulting in great damage to cohesion and coupling. A single responsibility usually means a single function, so do not implement too many functional points for a module to ensure that the entity has only one reason to cause it to change.

Unix is the perfect embodiment of this principle. Each program is independently responsible for a single thing. Windows is a negative example of this principle. Almost all programs are intertwined.

open/closed principle (OCP) – Opening and closing principles

On the development of the closed principle, the core idea is: The module is extensible, and can not be modified. In other words, the extension is open and the modification is closed.

Openness to expansion means that existing code can be extended to accommodate new situations when new requirements or changes are made. Closing a modification means that once the class has been designed, it can complete its work independently, without any modification to the class.

For object-oriented purposes, you need to rely on abstractions, not implementations, and this implementation is the "policy pattern" in 23 classic design patterns. For object-oriented programming, some APIs require you to pass in a function that you can extend, such as our C language qsort () allows you to provide a "comparator", a memory allocation for the container class in the STL, and a variety of threads in the ACE lock. For software, the browser's various plug-ins belong to the practice of this principle.

Liskov substitution principle (LSP) – The principle of the Richter substitution

Robert C. Martin, a software engineering master, reduced the principle of the Richter substitution to a word: "subtypes moment-in be substitutable for misspelling base types". That is, subclasses must be able to replace their base classes. That is, subclasses should be able to replace any base class that can appear, and the code will work properly after being replaced. Also, you should not have a condition in your code to judge a subclass type such as If/else. The Richter replacement principle LSP is an important guarantee for the code to conform to the open and closed principles. It is because of the interchangeability of subtypes that the modules of the parent type can be extended without modification.

So it seems a little dogmatic, and I highly recommend that you take a look at the two most classic cases of this principle-"squares are not rectangles" and "ostriches are not birds". Through these two cases, you will understand that the "Mo Zi Xiao" said-"tea, beauty Also, love tea, not the beauty of the people also ..." thieves, people also; Although the sister is a beautiful girl, she doesn't like the beauty. Thieves are human, but hate thieves doesn't mean they hate people. This principle allows you to consider not the relationship between semantic objects, but the context of the actual requirements.

In many cases, the relationship between our classes in the early stages of design is not very clear, and LSP gives us a benchmark for determining and designing relationships between classes: need not inherit, and how to design an inheritance relationship.

Interface segregation principle (ISP) – Interface Isolation principles

The interface isolation principle means that functionality is implemented in interfaces, not classes, and that using multiple specialized interfaces is preferable to using a single total interface.

For example, we have different ways of using computers, for example: writing, communication, watching movies, playing games, surfing the internet, programming, computing, data and so on, if we put these functions are declared in the computer pumping class inside, then, our netbook, PC, Server, notebook implementation class to implement all these interfaces, This is too complicated. So, we can isolate these functional interfaces, such as: Work learning interface, programming development interface, Internet Entertainment interface, computing and data service interface, so that our different functions of the computer can selectively inherit these interfaces.

This principle can enhance our "building blocks" software development. For the design, the various event listener and adapter in Java, for software development, different user rights have different functions, different versions have different functions, are the application of this principle.

Dependency inversion Principle (DIP) – dependency inversion principle

High-level modules should not rely on the implementation of low-level modules, but rely on high-level abstraction.

For example, the wall switch should not rely on the switch implementation of the light, but should rely on an abstract switch standard interface, so that when we expand the program, our switch can also control other different lights, or even different appliances. In other words, the lights and other electrical appliances inherit and implement our standard switch interface, and our switch manufacturers do not need to be concerned about what kind of equipment they want to control, just need to care about the standard switch standards. This is the dependency inversion principle.

This is as if the browser does not depend on the following Web server, which relies only on the HTTP protocol. This principle is too important, the Division of Society, Standardization is the embodiment of this design principle.

Reference: Http://en.wikipedia.org/wiki/Solid_ (object-oriented_design)

Common Closure principle (CCP) – The principle of common closure

All classes in a package should be closed for the same type of change. A change affects a package and affects all the classes in the package. A shorter version of this is that classes that are modified together should be grouped together (in the same package). If you have to modify the code in your application, we want all of the changes to take place in a package (modified and closed) rather than in a lot of packages. The CCP principle is to combine all the classes that need to be modified for some same reason into a package. If 2 classes are physically or conceptually closely connected, they usually change together, they should belong to the same package.

The CCP extends the "close" concept of the Open and closed principle (OCP) and, when modified for a reason, restricts the scope of the change to a minimum range of packages.

Reference: Http://c2.com/cgi/wiki?CommonClosurePrinciple

Common Reuse Principle (CRP) – Common reuse principle

All classes of the package are reused together. If you reuse one of these classes, reuse them all. In other words, classes that are not reused together should not be grouped together. The CRP principle helps us decide which classes should be placed in the same package. Relying on a package depends on what the package contains. When a package changes and a new version is released, all users using the package must verify their work in the new package environment, even if the part they are using has not changed. Because if the package contains a class that is not used, the user will have to upgrade the package and test the original functionality even if the user does not care if the class changes.

CCP Benefits The defenders of the system. CCP makes the package as large as possible (the CCP principle joins functional-related classes), and CRP makes the packet as small as possible (CRP principle excludes unused classes). Their starting point is different, but not conflicting.

Reference: Http://c2.com/cgi/wiki?CommonReusePrinciple

Yap principle– Hollywood principles

The Hollywood principle is a phrase-"Don t call us, we'll call you." It means that the Hollywood brokers don't want you to contact them, but they will contact you when they need it. That is, all components are passive, and all component initialization and invocation is handled by the container. The component is in a container and is managed by the container.

In simple terms, the relationship between the container control program, rather than the traditional implementation, by the program code directly manipulated. This is the so-called "control reversal" concept:

Instead of creating objects,

Describes how objects are created. In code, objects are not directly related to services, but containers are responsible for linking them together.

The control power is transferred from the application code to the external container, and the transfer of control is the so-called inversion.

The Hollywood principle is the fundamental principle of the IOC (inversion of control) or DI (Dependency injection). This principle is much like the dependency inversion principle, which relies on interfaces rather than instances, but how does this rule solve the problem of passing the instance into the calling class? You may declare it as a member, you can pass the constructor, you can pass the function arguments. But IOC allows you to create a physically configured class from a configuration file, a profile read by the service Container. But programs can also become unreadable, and the performance of programs is likely to fall.

Reference:

Http://en.wikipedia.org/wiki/Hollywood_Principlehttp://en.wikipedia.org/wiki/Inversion_of_ControlHigh Cohesion & Low/loose Coupling &– cohesion poly, low coupling

This principle is UNIX operating system design of the classic principle, the coupling between modules to the minimum, and strive to make a module to achieve excellence.

cohesion: A tightly coupled degree of integration of elements within a module: a measure of the degree of interconnection between different modules within a software structure

Cohesion means reuse and independence, and coupling means a domino effect that pulls the whole body.

Reference:

http://en.wikipedia.org/wiki/Coupling_ (computer_science) Http://en.wikipedia.org/wiki/Cohesion_ (computer_ Convention over revisit (CoC) – Convention superior to configuration principles

To put it simply, some accepted configurations and information are used as internal default rules. For example, the Hibernate mapping file, if the contract field name and class attributes are consistent, you can basically not have this configuration file. Your application only needs to specify convention information, thereby reducing a lot of convention and having to spend time and energy on long-winded stuff. Configuration files are very often quite impacting development efficiency.

There are very few profiles in rails (but not no, the database connection is a profile), and it is estimated that the Rails fans are 10 times times more efficient than Java developers. MAVEN also uses the COC principle, when you execute the mvn-compile command, you do not need to point to where the source file, and the compiled class file placed in where also did not specify, this is the COC principle.

Reference: Http://en.wikipedia.org/wiki/Convention_over_Configuration

separation of Concerns (SoC) – Separation of concerns

SoC is one of the most important goals in computer science. The principle is that in software development, through various means, the issue of the various concerns to separate. If a problem can be decomposed into independent and small problems, it is relatively easy to solve. The problem is too complex, there are too many points to focus on, and programmers are limited in their ability to focus on all aspects of the problem. Just as the programmer's memory is so limited to computer knowledge, the programmer's ability to solve problems is just as limited as the complexity of the problem to be solved. When we analyze the problem, if we mix all the things together to discuss, then there will only be a result-chaos.

I remember there was a project in the last company that was discussed for more than 1 years, the project was not complex, but without the use of SOC, all of the things confused, plus a bunch of programmers injected a variety of ideas and ideas, the whole project suddenly out of control. Finally, a 1-year project was originally done for 3 years.

There are two main ways to realize separation of concerns, one is standardization, the other is abstraction and packaging. Standardization is to develop a set of standards, so that users adhere to it, the behavior of people to unify, so that the use of the standard people do not have to worry about other people will have a lot of different implementations, so that their own procedures can not be matched with others. Java EE is a standard large collection. Each developer needs to focus on the standard itself and what he is doing. Just like the development of screw screws people only focus on the development of screw screws on the line, and do not pay attention to how the CAP is produced, anyway, the screwdriver and screw screws will be able to close to the standard. It is also a good way to realize separation of concerns by constantly packing some parts of the program. Once a function is drawn out and implemented, the person using the function does not have to care how the function is implemented, and once a class is drawn and implemented, the user of the class is not concerned about how the inner of the class is implemented. Concepts such as components, tiering, service-oriented, and so on are designed to be drawn and packaged at different levels so that the user does not care about its internal implementation details.

Plainly or "high cohesion, low coupling."

Reference: HTTP://SULONG.ME/ARCHIVES/99

Design by Contract (DbC)-Contract designs

The core idea of DBC is the interaction between elements in software system and the metaphor of "responsibility" and "obligation". This analogy comes from "clients" and "suppliers" in business activities. For example:

The

supplier must provide a product (liability) and he has the right to expect the customer to have paid (right). The customer must pay (responsibility) and be entitled to the product (right). Both parties must perform those responsibilities that are valid for all contracts, such as laws and regulations.

Similarly, if a module provides a function in programming, it wants to:

expects all client modules that invoke it to guarantee a certain entry condition: This is the prior condition of the module (the customer's obligations and the supplier's rights, so that it does not have to deal with situations that do not meet the prior conditions). Ensure that a specific attribute is given when exiting: This is the posteriori condition of the module-(the supplier's obligations, obviously the client's rights). Assume at the time of entry and maintain some specific attributes when exiting: invariant.

A contract is the formal form of these rights and obligations. We can use "three questions" to sum up the DBC, and as a designer to often ask:

What does it expect? What does it guarantee? What is it to keep?

According to the description of the DBC concept presented by Bertrand Meyer, for a method of class, there is a precondition and a subsequent condition, the precondition indicates the parameter data of the method, and the method can be invoked only if the precondition is satisfied. At the same time the subsequent condition is used to describe the state of the method completion, and if the execution of a method causes the subsequent condition of the method to be incorrect, then the method should not return normally.

Now that the prerequisites and subsequent conditions are applied to the inheritance subclass, the subclass method should satisfy:

prerequisites are not stronger than base classes. Subsequent conditions are not weaker than the base class.

In other words, when an object is invoked through the interface of a base class, the user knows only the base class prerequisites and subsequent conditions. Therefore, an inheriting class must not require a user to provide a stronger prerequisite than a base class method requires, i.e., that the inheriting class method accept any condition (parameter) that any base-class method can accept. Similarly, an inheriting class must conform to all subsequent conditions of the base class, i.e., the behavior and output of the inherited class method cannot violate any constraints established by the base class, and the user cannot be confused about the output of the inherited class method.

In this way, we have a contract based LSP, and the contractually based LSP is an enhancement of LSP.

Reference: Http://en.wikipedia.org/wiki/Design_by_contract

acyclic Dependencies Principle (ADP) – Non-ring dependency principle

The dependency structure between packages must be a direct, loop-free graphic, that is, loops (circular dependencies) are not allowed in the dependency structure. If the dependency of the package forms a ring structure, how do you break this cyclic dependency? There are 2 ways to break this cyclic dependency: The first method is to create a new package, and if a, B, C form a loop dependency, then extract the common class into a new package d. This turns C dependency a into C-dependent D and a-dependent d, which breaks the cyclic dependencies. The second approach is to use the dip (dependency inversion principle) and the ISP (interface separation principle) design principles.

The no-ring dependency principle (ADP) solves the coupling problem between packages. When designing a module, you cannot have a circular dependency.

Reference: Http://c2.com/cgi/wiki?AcyclicDependenciesPrinciple

————————————————————————————

These principles may be some of the academic school, may also be too theoretical, I said here is also more vague and simple, here is just to give you a general picture, if you want to know more things, we can Google more.

But these principles do not look difficult, but it is not so easy to use them well. To be able to use these principles with precision and without dogma, my experience is as follows: (I think this is a theory to the application of the process)

You can first understand these principles superficially or superficially. But don't rush to use it immediately. Observe and summarize others ' or own design in work study. Go back and review these principles, I believe you will have some experience. Practice it moderately. Goto Step 3rd.

I believe that there may be some principles in fact which we welcome.

(End of full text)

A source of http://coolshell.cn/articles/4535.html

Related Article

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.