In those years, the air seems to be able to smell the Han and Tang dynasties, so you never allow your face shiny, always stay alive. However, you must have felt troubled by these "advanced terms". Perhaps today, you still smattering them. But today, it's all going to change completely! I will lead you to a new high-definition perspective into the wonderful world of programming, and enjoy the lively atmosphere of Han swimming in these "advanced terms", as well as the cloud-water zen heart of fluttering yuqingping.
•
Internal cohesion
Cohesion, popular speaking, is their own things to keep, their own things to do.
Classic theory tells us two major elements of a program: one is data and the other is opration. and pascal 's parent nicklaus wirth the well-known formula "program = data structure + algorithm" is further proposed. Although the formulation is different, but its fundamental connotation is consistent, the subtle difference is that "data + operation" is the microscopic field of view, "Structure + algorithm" is the perspective of the field of view. And in the macroscopic view, I think "program = object + Message". What is the object? object is to take care of their own things, do their own things of the program module-this is the cohesion! The traditional process-oriented programming method, because of the fragmented data structure and algorithm, makes the software's cohesion generally depressed, which once caused the software crisis. Imagine, everyone's own things do not take good care of their own things do not do well, do not cause a crisis just blame it! Of course, the object of the cohesion is only a level of cohesion, in different scales in fact there is a requirement for cohesion, such as the method must also be said to be cohesive, the architecture must be said to be cohesive.
"Zhouyi, Hog Biography," said the "dry road changes, the lives of all, the preservation of Taihe, is cheer", is to require each individual with their own endowments and strive to achieve their own character, and then their respective preservation, mutual and together, and finally reached the perfect state of the universe. The Analects of Confucius and the Zi Lu asked the gentleman. The son said: "Repair oneself with respect." "Yue:" So? "Yue:" to repair their own to the people, it is clear to teach us to constantly improve their cohesion, to minimize the trouble caused to others, so as to achieve the goal of the people, Ann, the world. I think the process of growing up is a process of increasing cohesion. "Their own things to keep, their own things to do", these childhood teachings, put today can still make a lot of "adults" blush unceasingly. Too many people do not keep their own "things", the safekeeping of their own body, the custody of their marriage is not good, but also not good for their own like Spider-like chatter of the frantic heart. As for doing their own things, it is more disconsolate, even a lot of people even their own things are not clear, so vegetates. Cohesion is a problem that deserves our good reflection.
• dependence • Coupling
In object-oriented programming, the object itself is cohesive, is to take care of their own data, to complete their own operations, and to the outside world to show their own state and behavior. However, there is no absolute self-reliance, the opening up is necessary! An object that often involves dealing with other objects, including the state of other objects, and the behavior of relying on other objects, and once that happens, we call the object dependent on another object. As long as there is a relationship between the two objects on one side, we call the coupling between the two objects. such as mother and baby, mother should always pay attention to baby's sleep, Wake, sleepy, crying, urine and so on, baby to rely on mother's feeding, coax sleep, change diapers and other behavior, from the meaning of the program, the two interdependent, so there is also coupling. The first thing to say is that coupling is necessary. Let's take a look at the following experiment.
"Wang Yangming and the flower of the mountain"
Class FlowersInMountain
{
Public bool IsBloomed//full bloom
{
Get { return true; }
}
}
Class WangYangMing
{
/// <summary>
/// Wang Yangming Huiji Mountain Flower
/// </summary>
/// <returns>Hills are in full bloom</returns>
Public bool AdmireFlowers()
{
Return ?;
}
}
Static void Main()
{
WangYangMing wym = new WangYangMing();
FlowersInMountain flower = new FlowersInMountain();
If (wym.AdmireFlowers())
{
MessageBox.Show("I saw the mountain flower open!");
}
Else
{
MessageBox.Show("I saw the mountain flower not open!");
}
}
because Wang Yangming this object does not rely on Shanhua this object, and there is no other way to know the blooming state of the flower, so he either choose not to say, or nonsense, but not to say that the compilation is a pass, and nonsense as Wang Yangming is also pass, so this system is unable to set up. To set up the system, you have to write this:
public bool AdmireFlowers()
{ return flower.IsBloomed; ;
}
Regardless of how the object of the flower, as a parameter passed in or as a property set, or in the internal structure, in short, Wang Yangming and the mountain flower between the dependence between the two produced a coupling. of course, this is a very superficial question. What is interesting is Wang Yangming's view of the matter: "When you are not looking at the flowers, the flowers are in silence with you; See nothing outside the heart! "Wang Yangming is right!" he said. "Nothing Outside the Heart" translation technical language is this: there is no coupling of the two objects must not get the other side of the reference!
• Coupling degree, decoupling
The degree of coupling is the degree of coupling, which is the extent to which both sides depend. The above mentioned mother and baby is strong coupling. And between you and express brother is weak coupling. In general, coupling through high is not a good thing. Take it as the IT elite of you, the superiors always urge you to work progress, novice frequently need you to guide the problem, go out also need to participate in Wine Bureau dinner, and then every day to see the face of leadership, pay attention to the mood of the wife, and then you have to pay attention to the code bug ,bug ,bugs, and requirements change, change, change, are enough to burn, but also caught off guard to pay attention to the eyes, cervical spine, prostate and hair status, and then you fry a stock, these add up is probably a strong coupling. In a sense, coupling is inherently hostile to freedom, whether other objects depend on you, or if you rely on other objects. For example, people who smoke, drink, how much you depend on them is not free, for example, some people have seven or eight kids in the family, as well as elderly parents, father-in-law mother, they depend on you, you are more than freedom. So Lao Tzu said: "Tone deaf is deaf, colored blind, the gallop of hunting is crazy, the rare goods is a nuisance." Rousseau is also not without Sadness said, "Life and freedom, but not to the yoke." Therefore, to be free, it is necessary to reduce the coupling, and this process is called decoupling and.
• Dependency inversion (dependence inversion Principle)
decoupling and the most important principle is the dependency inversion principle:
high-level modules should not rely on the underlying modules, they should all rely on abstraction. Abstractions should not be dependent on detail, and detail should be dependent on abstraction.
"Capital" has been explained by the principle of dependence reversal-in the infancy of commodity economy, there has been a barter exchange. Suppose you want to buy an iphone, the boss who sells the iphone lets you trade a pig with him, but you don't have a pig, you only program. So you find a pig farmer, said to make a pig-raising app for him to change a pig, he said change pig can, but have to use a gold necklace to exchange-so here there is a series of object dependence, resulting in a serious coupling disaster. The best way to solve this problem is that both buying and selling are dependent on abstraction-that is, money-to exchange, so the coupling is greatly reduced.
Another example of dependency inversion in programming. We know that in communication, the delivery of messages and the processing of messages are often inseparable. In the case of a general communication framework, the sending and receiving of messages is usually implemented, and the processing of messages requires the user to be customized. Let's look at an example of a forward dependency: the Lightweight communications engine striveengine. Tcpserverengine is StriveEngine.dll provides a communications engine that publishes a messagereceived event. Assuming that I have defined a Customizehandler class for message processing, the interior of Customizehandler needs to be scheduled Tcpserverengine messagereceived events, So Customizehandler relies on tcpserverengine, which is a common dependency, which is that high-level modules rely on lower-layer modules.
The esframework Communication Framework applies the principle of dependency reversal. Esframework defines a Icustomizehandler interface that is implemented by the user when the message is processed, and then injected into the Rapidpassiveengine client communication engine.
class CustomizeHandler: ICustomizeHandler
{
public void HandleInformation(string sourceUserID, int informationType, byte[] info)
{
······
}
public byte[] HandleQuery(string sourceUserID, int informationType, byte[] info)
{
······
}
}
IRapidPassiveEngine rapidPassiveEngine = ESPlus.Rapid.RapidEngineFactory.CreatePassiveEngine();
CustomizeHandler customizeHandler = new CustomizeHandler();
rapidPassiveEngine.Initialize("ID", "passWord", "127.0.0.1", 9000, customizeHandler);
Obviously, compared to the previous example, the dependencies here become rapidpassiveengine dependent on customizehandler, that is, dependencies are inverted, and the upper modules are no longer dependent on the underlying modules, but they are both dependent on abstraction. Rapidpassiveengine depends on the parameters of the Icustomizehandler interface type, and Customizehandler is also dependent on icustomizehandler--in the way it implements the interface, which is a paradigm of dependency inversion.
• Controlled inversion (inversion
of control)
control inversion and dependency inversion are the same two concepts, and there are often inversion of control when there is dependency inversion. But control reversal also has its own unique connotation.
First, we need to differentiate between two roles, server and client, which is the service and client side. The party providing the service is called the Service party, and the party requesting the service is called the client side. Our most familiar examples are the C/s architecture of distributed applications, the service side and the client. In fact, in addition, C/s relationship everywhere visible. For example, in the TCP/IP protocol stack, we know that each layer of protocol to serve the previous layer, then this is a C/s relationship. When we use the development framework, the development framework is the service side, and the business application we write ourselves is the client side. When the client calls the server, this is called general control, and when the server calls the client, it is what we call the inversion of control, and we call it "callback". Inversion of control and dependency inversion are all a kind of programming idea, the dependency inversion is in the form of call, and control inversion is the control of the program flow. In general, the control of the program belongs to the server, and once control is handed to the client, it is called inversion of control. For example, you go to a restaurant, you are the client, the server. You order, the restaurant is responsible for cooking, the control of the program flow belongs to the server, and if you go to the cafeteria, the control of the program flow is transferred to the client, that is, control reversal.
The idea of inversion of control is embodied in many fields. For example, the release/subscription of events is a kind of control inversion, Gof design mode also embodies a number of control inversion, such as the typical template method pattern. The development framework is a concentrated embodiment of the application of the control inversion thought. For example, as previously mentioned in the esframework Communication Framework , the communication engine callback the user-defined message handler, which is a control reversal. and Esframework callback user-defined group relationships and friends, callback user-defined User Manager to manage online user-related status, callback user-defined login verification processing, and so on. Another example is the Lightweight communications engine striveenginewith esframework same strain, which enables more flexible communication by recalling user-defined communication protocols.
From this we can also summarize the difference between the development framework and the class Library: When using the development framework, the framework grasps the control of the program flow, while using the class library is the application control of the program flow. In other words, when using a framework, the main loop of the program is in the framework, and when you use a class library, the main loop of the program is in the application. The framework callbacks the application, and the class library does not call back the application. The main objects in Esframework and Striveengine are named after the engine, and we can see that the framework controls the main loop of the program-it will hold the direction for you, look ahead, and easily navigate!
• Dependency Injection (Dependency injection
)
The relationship between dependency injection and dependency inversion and inversion of control is still a universal one. Dependency injection, in its broadest sense, is to gain dependence by "injecting" the way. We know that a object relies on a B object, which is equivalent to a "call" to a B object inside a object, provided that a reference to the B object is obtained inside a object. A reference to a B object is derived from the following: A object is created internally (whether as a field or as a temporary variable), constructor injection, attribute injection, method injection. The next three ways are collectively referred to as "dependency injection", and the first way I have sporogenous a noun, called "dependent endogenous", is that the fundamental difference is whether the creation of the object I depend on is done by myself. Of course, this is the concept of a generalized dependency injection, which we would not normally use. What we usually use is the narrow concept of dependency injection. However, the direct statement of its definition may be too flexor, and we will still look at the concrete examples.
For example, OMCS network voice video frame , it realizes the multimedia equipment (microphone, camera, desktop, electronic whiteboard) collection, encoding, network transmission, decoding, playback (or display) and other related set of processes, can quickly develop a video chat system, Video conferencing system, Remote medical system, distance education system, network monitoring system and so on network multimedia application system. However, Omcs directly supports universal voice and video devices, and in some systems, a webcam or a special video capture card as a source of video, or other sound acquisition device as an audio source, Omcs provides an extension interface-the user's own extension interface, and then "dependency Injection" method to inject an object instance into the Omcs, which completes the expansion of the audio and video devices.
"Dependency Injection" is often used for scaling, especially in the design of the development framework. In a sense, any development framework is inherently an incomplete application. Therefore, an excellent development framework not only allows developers to reuse these proven and outstanding solutions, but also enables developers to insert custom business logic into the framework, thus flexibly adapting to the needs of a particular business scenario-that is, to be well-extensible. For example, the above mentioned Omcs network voice video frame can be applied to audio, video chat system, video conferencing system, telemedicine system, distance education system, network monitoring system and so on based on network multimedia application system; esframework Communication Framework can be applied to instant messaging systems, large multiplayer online games, online web games, file transfer systems, data acquisition systems, distributed OA systems, and any software systems that require distributed communications-this good extensibility is inseparable from the use of "Dependency injection"!
• Interface-oriented programming
Speaking of the end, "interface-oriented programming" is already on the horizon. Whether it is dependency inversion, inversion of control, or dependency injection, the idea of "interface-oriented programming" is already contained. Interface-oriented means that it is oriented toward abstraction. As a philosophical category, the prescriptive less is called abstraction, and the prescriptive is more specific. And the interface is a typical "abstract" form in the program. To abstract, it means to face the essential stipulation of the thing, to get rid of the perceptual heteropoly, and to grasp the "necessity"--which in itself means freedom, because freedom is the understanding of necessity.
Perhaps the above-mentioned paragraph is too "philosophical", but "one's reason" and "Wanshu" itself "not two"-in summary, dependence inversion, control inversion, dependency injection are all around the "decoupling and" the problem, but at the same time are "interface-oriented programming" approach-therefore, "interface-oriented programming" is inherently "decoupled and" a good way to do it. This also confirms the dialectical derivation of the category from "abstraction" to "freedom".
"Object-oriented" and "interface-oriented" is not two different methods, "interface-oriented" is actually "object-oriented" intrinsic requirements, is a part of the connotation of the central expression. Our expectations for ideal software are often summed up as "high cohesion, low coupling", which is the goal of the entire modern software development methodology. Object-oriented methodology, as the representative of modern software development methodology, contains the thought essence of "high cohesion, low coupling", in this sense, the expression "object oriented" is more focused on "high cohesion", "interface oriented" expression is more focused on "low coupling"-but the same thing different side.
In addition, we can also from the "interface-oriented programming" of the idea of "secular" enlightenment-"The Analects of Confucius," There is no place, suffering so stand, do not suffer from the ignorance of people, suffering from it can not also-is to teach us to face "I have the ability?" "I have no ability?" "Such an interface, not oriented" Have I got a seat? "," Others do not understand me? "Such a concrete. In my view, this is a great lesson!
The advanced terminology that those years don't understand--dependency inversion? Control inversion? Interface-oriented programming