Principles of Software Design

Source: Internet
Author: User
Tags what parameter

Don ' t Repeat yourself (DRY)

DRY is one of the simplest laws and is the easiest to understand. But it can also be the hardest to apply (because to do so, we need to do a lot of work on 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 generality into a unique new method, and change the existing code so that they can 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 respected in design, home design, interface design, operation and design, complex things are more and more in the people's BS, and simple things are increasingly recognized, such as the design of these UI and our Chinese Web page (especially Sina Web page) is a negative example. "Ikea" (IKEA) simple, efficient home design, production ideas, "Microsoft" (Microsoft) "WYSIWYG" concept; "Google" (Google) simple, direct business style, without exception to follow the "kiss" principle, is also the "kiss" principle, These seemingly magical business classics have been fulfilled. And Apple's Iphone/ipad the principle to the extreme.

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

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

Program to a interface, not an implementation

This is the most fundamental philosophy in design patterns, focusing on interfaces rather than implementations, relying on interfaces, rather than implementations. Interfaces are abstractions that are stable, and implementations are varied. The principle of dependency inversion, which we will look at later in our object-oriented solid principles, is another form of this principle. There is also a principle called composition over inheritance(like combination rather than inheritance), these two are the design principles in 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 is to change the state of an object, it has the nature of the command;

Typically, a method may be a pure command mode or a pure query mode, or a mixture of the two. When designing the interface, if possible, should try to make the interface single, to ensure that the behavior of the method is strictly a command or query, so that the query method does not change the state of the object, no side effects, and change the state of the object can not have a return value. That is: if we are to ask a question, then it should not affect its answer. In practice, it is necessary to weigh the clarity of semantics and the simplicity of use, depending on the situation. Combining command and query functionality into a single method facilitates customer use, but reduces clarity, and may not facilitate assertion-based programming and requires a variable to hold the query results.

In the system design, many systems are also designed in such a way, the function of querying and the system separation of command function, so that the system performance, but also conducive to the security of the system.

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

You Ain ' t gonna need It (YAGNI)

This principle, in short, is to consider and design only the necessary functions to avoid over-design. Just implement the features you currently need, and you can add them later when you need more features.

    • Do not add complexity if it is not necessary.
    • Software development is first a communication game.

The previous site has an article on excessive refactoring, this example is a counter-example of this principle. And, the designer of WebSphere has said that he has over-engineered the product. When designing a system, our programmers or architects consider a lot of extensibility, leading to a lot of tradeoffs in architecture and design, and ultimately to project failure. This is a very ironic lesson, as it would have been desirable to prolong the life cycle of the project as much as possible, rather shortening the life cycle.

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

Law of demeter– Dimitri

Dimitri (Law of Demeter), also known as the "least knowledge Principle" (Principle of Least knowledge), was derived from a project called Demeter at the University of the Netherlands in 1987. Craig Larman called Law of Demeter "Don't Talk to strangers." The chapter on LOD in the path of programmer's cultivation is called the "decoupling and Dimitri Law". There are some very figurative metaphors about the Dimitri law:

    • If you want your dog to run, would you say it to the dog or four legs?
    • If you go to the store to buy things, will you give the money to the clerk, or will you hand over the purse to the clerk to get his own?

Talking to the dog's limbs? Get the clerk to take the money out of his wallet? This may sound ridiculous, but in our code it's pretty much a bit of a deal.

For LOD, the formal statement is as follows:

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

  1. Object o;
  2. Component Object directly related to O;
  3. An object created or instantiated by method m;
  4. An object that is the parameter of the method M.

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

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

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

In the "refactoring" Book of 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, always envious of the members, structures, or functions of other objects, calling people's things from afar. Such a structure is obviously unreasonable. Our program should be more "shy" in writing. You cannot take the money out of the guest's purse, as in the previous example, the clerk who does not treat himself as an outsider. The "shy" program only talks to your closest friends. In this case, the structure of the program should be adjusted so that the object has its own feature of envy, or use a reasonable design pattern (e.g. facade and mediator).

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

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

In general, this is the five-object-oriented design principles, but I think these principles can be applied to all software development.

Single Responsibility Principle (SRP) – Principle of sole responsibility

With regard to the principle of single responsibility, the core of the idea is: a class, only one thing, and to do this thing well, it only a cause of its change . The principle of single responsibility can be regarded as the extension of low-coupling, cohesion-poly in object-oriented principle, and defines responsibility as the cause of change, in order to improve cohesion to reduce the cause of change. The more responsibilities that may cause it to change, the more it will lead to a dependency on responsibility, which has an impact on each other, thus greatly damaging the cohesion and coupling degree. A single responsibility usually implies a single function, so do not implement too many functional points for a module to ensure that the entity has only one cause for it to change.

    • Unix/linux 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 of the programs are interwoven and coupled together.

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

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

    • Opening up to extensions means that existing code can be extended to accommodate new situations when there are new requirements or changes.
    • Enclosing a modification means that once the class is designed, it can do its work independently, rather than making any modifications to the class.

For object-oriented, you need to rely on abstraction, not implementation, and the "policy pattern" in 23 classic design patterns is the implementation. For non-object-oriented programming, some APIs require you to pass in a function that you can extend, such as the qsort () of our C language, which allows you to provide a "comparator", a memory allocation for the container class in the STL, and a variety of multi-threaded locks in the ace. For software, the browser's various plugins belong to this principle of practice.

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

The Master of Software Engineering, Robert C. Martin, finally reduced the principle of the Richter substitution to a sentence: "Subtypes must is substitutable for their base types". That is, subclasses must be able to replace them with their base classes. That is, subclasses should be able to replace where any base class can appear, and after being replaced, the code will work correctly. In addition, you should not have the criteria for judging a subclass type such as If/else in your code. The Richter replacement principle LSP is an important guarantee for the code to conform to the open and closed principle. It is because of the replaceable nature of subtypes that the modules of the parent type can be extended without modification.

So, it seems a bit dogmatic, I very much suggest you look at this principle of the two most classic case-"square is not a rectangle" and "ostrich is not a bird." Through these two cases, you will understand the "Mo-zi" in the said-"Di, Beauty, love, not the beauty of people also ..." Thieves, people also, bad thieves, not the wicked also. "--although the sister is a beauty, but like a sister does not mean like beauty. Thieves are people, but hate thieves doesn't mean they hate humans. This principle allows you to consider not the relationship between the semantic objects, but the actual requirements of the environment .

In many cases, the relationship between our classes is not very clear at the beginning of the design period, and the LSP gives us a baseline for judging and designing the relationship between classes: the need to inherit, and how to design the inheritance relationship.

Interface segregation Principle (ISP) – Interface Isolation principle

The principle of interface isolation means that functions are implemented in interfaces rather than classes, and using multiple specialized interfaces is better than using a single total interface.

For example, we have different ways of using computers, such as: writing, communication, watching movies, playing games, surfing the internet, programming, computing, data, etc., if we declare these functions in the computer's pumping class, then, our netbook, PC, Server, notebook implementation class are to achieve all of these interfaces, It's too complicated. Therefore, 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 improve our "building blocks" of 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 rather on high-layer abstractions.

For example, the wall switch should not rely on the switch implementation of the lamp, but should rely on an abstract switch standard interface, so that when we extend the program, our switch can also control other different lights, and even different electrical appliances. That is, electric lights and other electrical appliances inherit and implement our standard switching interfaces, and our switch producers do not need to be concerned about what kind of equipment they want to control, just care about that standard switch standard. This is the dependency inversion principle.

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

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

Common Closure Principle (CCP) – Common closure principle

All classes in a package should be closed for changes of the same type. A change affects a package, which affects all classes in the package. A shorter argument is that classes that are modified together should be grouped together (in the same package). If you have to modify the code in the application, we want all of the changes to occur in one package (modify close) instead of being spread over many packages. The CCP principle is to combine all classes that need to be modified for the same reason in a package. If 2 classes are physically or conceptually interconnected, they usually change together, and they should belong to the same package.

CCP extends the "off" concept of the Open/closed principle (OCP) and restricts the scope of changes needed to a minimum range of packages for a reason that needs to be modified.

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

Common Reuse Principle (CRP) – Principle of common reuse

All classes of the package are reused together. If you reuse one of these classes, reuse 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 is dependent on everything that the package contains. When a package has changed and a new version is released, all users who use 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 classes that are not used, the user will have to upgrade the package and re-test the original functionality even if the user does not care if the class has changed.

CCP benefits the maintainer of the system. CCP makes the package as large as possible (CCP principle joins function-related classes), and CRP makes the packet as small as possible (the CRP principle rejects unused classes). They have different starting points, but they do not conflict with each other.

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

Hollywood principle– Hollywood Principles

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

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

    1. Instead of creating an object, it describes how the object was created.
    2. In code, objects are not directly related to the service, but rather the container is responsible for linking them together.

Control is transferred from the application code to the external container, and the transfer of control is called reversal.

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 principle solve the problem of passing this instance into the calling class? You may declare it as a member, and you can pass the function arguments through the constructor. But IOC allows you to generate the actual configured class through a configuration file, a configuration file read by the service Container. However, the program may also become unreadable, and the performance of the program may also be degraded.

Reference :

    • Http://en.wikipedia.org/wiki/Hollywood_Principle
    • Http://en.wikipedia.org/wiki/Inversion_of_Control
High Cohesion & low/loose coupling &– cohesion poly, low coupling

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

    • Cohesion: the degree to which each element in a module is bonded to each other
    • Coupling: A measure of the degree of interconnection between different modules within a software architecture

Cohesion means reuse and independence, and coupling means a domino effect that leads to a full body.

Reference :

    • Http://en.wikipedia.org/wiki/Coupling_%28computer_science%29
    • Http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29
Convention over Configuration (CoC) – formula is better than the collocation principle

To put it simply, some of the accepted configuration and information are used as internal default rules. For example, Hibernate's mapping file, if the contract field name and class attributes are consistent, basically can not do this configuration file. Your app only needs to specify convention information, which reduces a lot of convention and has to spend time and effort on the long-winded stuff. Configuration files often have a considerable impact on development efficiency.

There are few profiles in rails (but not no, database connection is a profile), and rails ' fans are 10 times times more efficient than Java development, which is probably the reason. MAVEN also uses the COC principle, when you execute the mvn-compile command, you do not need to refer to where the source files are placed, and after the compilation of the class file is not specified anywhere, 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 efforts in computer science. This principle is in software development, through various means, the problem of the various points of concern. If a problem can be broken down into independent and minor problems, it is relatively easy to solve. The problem is too complex, there are too many things to focus on to solve the problem, and the programmer's ability is limited, not at the same time 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 everything together, then there will only be one result-chaos.

I remember having a project in the last company that was discussed for over 1 years, the project was not complicated, but without the use of the SOC, the whole thing was mixed up, and a bunch of programmers injected different ideas and ideas, the whole project went out of control all of a sudden. 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 the development of a set of standards, so that users abide by it, the behavior of people to unify, so that the use of standard people do not have to worry about other people will have a lot of different implementations, so that their program can not be with others. Java EE is a large collection of standards. Every developer needs to focus on the standard itself and what he's doing. Like the development of screws silk nails people only focus on the development of screws silk nails on the line, without concern about screws hat is how to produce, anyway screws cap and screws silk nails according to the standard will be able to close. It is also a good way to realize separation of concerns by constantly packaging some parts of the program. Once a function has been pumped out and implemented, the person using the function does not care how the function is implemented, and similarly, once a class is drawn and implemented, the user of the class does not have to focus on how the class is implemented internally. Concepts such as components, hierarchies, service orientation, and so on are all 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-based technology

The core idea of DBC is the analogy between the elements of a software system and the "responsibility" and "obligation". This metaphor is derived from the "Customer" and "supplier" in the business activity. 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 (liability) and be entitled to the product (rights).
    • The parties to the contract must fulfil those responsibilities that are valid for all contracts, such as laws and regulations.

Similarly, if a module provides a function in the program design, it wants to:

    • It is expected that all client modules that call it will be guaranteed a certain entry condition: This is the pre-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 specific attributes are given when exiting: This is the post-condition of the module-(the supplier's obligations, obviously the customer's rights).
    • Assume on entry and maintain some specific properties on exit: invariant.

A contract is a formal form of these rights and obligations. We can summarize DBC with "three questions", and as designers often ask:

    • What is it looking for?
    • What does it have to guarantee?
    • What is it to keep?

According to Bertrand Meyer's description of the DBC concept, for a method of a class, there is a precondition and a follow-up condition, the precondition indicates what parameter data the method accepts, and the method can be called only if the precondition is satisfied. At the same time, subsequent conditions are used to illustrate the state of the method when it is completed, and this method should not return normally if the execution of a method causes the subsequent condition of the method to be non-valid.

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

    1. The precondition is not stronger than the base class.
    2. Subsequent conditions are not weaker than the base class.

In other words, when an object is called through the interface of the base class, the user knows only the base class prerequisites and subsequent conditions. Therefore, inheriting classes must not require the user to provide a stronger precondition than the base class method requires, that is, the inheriting class method has to accept any conditions (parameters) acceptable to any base class method. Similarly, inheriting classes must conform to all subsequent conditions of the base class, that is, the behavior and output of the inheriting class methods should not violate any constraints established by the base class, and the user cannot be confused about the output of inheriting class methods.

Thus, we have a contract-based LSP, and the contract-based LSP is an enhancement of the LSP.

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

Acyclic Dependencies Principle (ADP) – The principle of non-cyclic reliance

The dependency structure between packages must be a direct, loop-free graph, that is, loops (cyclic dependencies) are not allowed in the dependency structure. If the dependency of a package forms a ring structure, how do you break this cycle dependency? There are 2 ways to break this circular dependency: the first is to create a new package, and if a, B, and C form loop-dependent, then pull these common classes out into a new package d. In this way, C dependency a becomes C dependent D and a relies on D, thus breaking the cyclic dependency. The second approach is to use the dip (dependency inversion principle) and the ISP (interface separation principle) design principles.

The non-cyclic dependency principle (ADP) solves the problem of coupling between packages. You cannot have circular dependencies when designing a module.

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

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

The above principles may be some college school, but also may be too theoretical, I said here is also relatively vague and simple, here is just a general picture, if you want to know more things, we can more Google a bit.

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

    1. You can know these principles first, superficially, or outwardly.
    2. But don't rush to use it right away.
    3. Observe and summarize the design of others or yourself in the study of work.
    4. Go back and look at these principles, I believe you will have some of your own experience.
    5. Have a moderate to practice a bit.
    6. Goto Step 3rd.

Principles of Software Design

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.