java - 软件工程中的耦合性和解耦合性是什么意思?
阿神
阿神 2017-04-17 13:01:47
0
8
1578
阿神
阿神

闭关修行中......

reply all(8)
Peter_Zhu

Don’t kill “coupling” with one stick. Coupling is a broad concept. The relationship between two program modules is called coupling.

Some modules must be associated to work. This is determined by business logic and cannot be denied. Therefore, Decoupling does not mean tearing down the association in a literal sense, but relaxing the association between modules to the necessary extent. Some suggestions:

  • The module only exposes the minimum interface to the outside world, forming the lowest dependencies.
  • As long as the external interface remains unchanged, modifications within the module must not affect other modules;
  • Deleting a module should only affect other modules that have dependencies, and should not affect other irrelevant parts;

There is an iron law in software engineering "High cohesion, low coupling" This is the truth: necessary coupling is undeniable, and nothing can be done without coupling programs; but unnecessary tight coupling will Let the program "move one hair and affect the whole body", ultimately making it impossible for programmers to write and maintain.

Humans can only focus on a small part of the content at the same time. "High cohesion, low coupling" is to meet this characteristic of human beings - only focusing on one module on a small scale can carry out local coding work. Only by converting specific codes into some abstract "modules" and "dependencies" on a large scale can we focus on the big and let go of the small, grasp the context of the program, and put together a complete product.

Imagine the model of "social division of labor" - each small unit only focuses on its own business part, and only has business outsourcing relationships with other units, as well as material and information interactions. Facts have proven that this model is orders of magnitude more efficient than the previous large state-owned enterprises that managed various functional departments on their own. This is the embodiment of "high cohesion, low coupling" in the real world.

Program is the second world created by human beings. The logic of program is nothing more than an abstraction of the laws of the world. If you jump out of the program and look at the program, you will find different perspectives and perspectives.

阿神

I’ll also explain it in layman’s terms, please don’t criticize if it’s not good.

Simple summary: Coupling is the relationship between one part of the program and other parts. Decoupling is to straighten out necessary coupling while minimizing unnecessary coupling (this sentence is actually a popular explanation of high cohesion and low coupling).

How you view coupling depends on the perspective and level from which you view a program. If you are looking at the internal implementation of a function or a class, this granularity is very fine. At this time, what you may be focusing on is how to write the function/class beautifully so that it has correct functions and is easy to understand at the same time. You can improve it by improving the layout of the code, optimizing the algorithm, encapsulating repeated operations into a new function, giving variables or functions more meaningful names, etc.

These methods can be said to be related to "high cohesion and low coupling". Improve code layout: Make the code more code-like, making it easier for people to see the function and intention of each code line. Appropriate name: If you name a variable variable, semantically speaking it can store any value. Its ambiguous name makes it difficult to distinguish its relationship with other parts of the code (unnecessary coupling with other parts) ), which can leave people reading the code at a loss. Making variable names more meaningful is actually a manifestation of high cohesion, that is, what you want this variable to do, others can see at a glance. Not to mention the extraction function.

If you are designing a module, you may be concerned about the classes and objects in the module, that is, how to make the relationship between classes and objects in the module simpler and clearer. The book "Design Patterns" by the Gang of Four is mainly about this. Each pattern in it is to find ways to reduce the coupling between classes and objects.

So if you are designing a system, you may not care about the classes (at least not at the beginning). You should focus on how many modules the system can be divided into and how each module is put together. (the term is called "collaboration") constitutes the whole system and other issues. If the module you design also needs to pay attention to the implementation details of other modules, then your system will fail.

So, no matter what your perspective is, the level of concern is high or low, and it is necessary to reduce complexity. This is the core idea of ​​coupling and decoupling.

It is said that any metaphor is lame, but I still want to give an example of extremely high efficiency and low coupling in reality, and that is the military. A country's army can range from tens of thousands to millions. For such a huge system, its efficiency is surprisingly high. Why? Simply put, this is due to several of its operating principles:

Strict discipline and strict rules and regulations
There will be no embarrassing situation where the superiors issue an order but cannot find someone to carry it out, or find someone who is unwilling to do it (very cohesive but not)

The command does not cross levels
Unless there are special circumstances, orders are conveyed through direct superiors. The commander rarely looks for small soldiers to do things alone (each level is highly cohesive in the eyes of the previous level. At the same time, leaders such as company commanders, squad leaders, and regiment leaders act as An interface at this level, the upper level only sends commands to the lower level through the interface)
Some people say that if the commander directly asks the soldiers to do things for him, wouldn't it be more efficient than communicating level by level? no! Why? There are several reasons (note that they can all be related to the principles we use when programming, so everything is thought through)

  1. The orders issued by the commander are usually very large tasks, often spanning many units and even arms. Wouldn’t it be exhausting to ask the commander to notify them one by one? (High-level abstractions should not be directly coupled to low-level implementations)

  2. If arbitrary cross-level orders are allowed to be issued, it is very likely that multiple superiors will issue different orders to a soldier at the same time. Then won’t the soldier be exhausted? (Resulting in inconsistent system status, or uneven busyness of the distributed system)

  3. Communication between soldiers and their direct superiors is usually barrier-free, but it is difficult to say across ranks. Only his direct superior knows best which soldier is good at what. When issuing orders across levels, it may lead to a decrease in task completion efficiency or even failure to complete the task (high-level abstractions often have difficulty in controlling the underlying details, leading to improper use or even misuse)

Clear division of functions
The army will divide the responsibilities of the entire army according to regions, time zones, departments, arms, etc. In this way, the entire army is divided into small parts with clear responsibilities, layer by layer, piece by piece. Each part is relatively independent and forms an organic whole. Therefore, it is difficult to think about being efficient.

巴扎黑

You're on a helicopter tour of the Grand Canyon when the pilot - who apparently made the mistake of eating fish, his lunch - suddenly groans and passes out. Luckily, he left you 100 feet above the ground. You reason that the lift rod controls total lift, so lowering it slightly will lower the helicopter gently toward the ground. However, when you do this, you discover that life is not that simple. The helicopter's nose pointed downwards and began to spiral left. Suddenly you realize that all the control inputs to the system you're driving have secondary effects. To depress the left hand lever, you need to compensatingly move the right handle back and press the right pedal. But each of these changes will again affect all the other controls. Suddenly, you're juggling an incredibly complex system where every change affects every other input. Your workload is enormous: your hands and feet are constantly moving, trying to balance all the interacting forces.

——"The Cultivation of Programmers" I think all programmers should read it and re-read it every year

左手右手慢动作

Coupling is unnecessary dependency, and its existence makes code reuse difficult. For example:

A class called OrderService is responsible for processing orders. Calling its createOrder() method will send a text message to the customer while creating the order. This coupling leads to when I want to create an order but don’t want to send a text message. At that time, I couldn't find any code that could be reused unless the logic of sending text messages was removed from createOrder().

阿神

For example, writing onclick=foo() on a certain p on the front-end HTML page is coupling.
Writing $("#id").click= xxx is decoupling.

迷茫

I think the questioner's confusion is not that he can't find the answer, but that the answer is too professional and not easy to understand. The above answer is actually too "professional".
Concepts in software often have their counterparts in hardware, and hardware is more visual and easier to understand.
If you have experience doing electrical experiments, this concept is easy to explain. The wiring between two circuit boards is coupling. The more wiring there are, the more complex the circuit becomes, so much so that even the circuit designer himself is confused. Once an error is discovered, there are too many clues and it is difficult to sort out, which is the so-called maintainability. It will also become more difficult to connect more boards to the circuit, which means the so-called scalability will become worse. Even if the circuit is barely connected, the same wiring method will be difficult to copy in other circuits, which is called poor reusability. This is the disadvantage of high coupling.
Although coupling has all kinds of disadvantages, it is inevitable because it cannot run without a coupling circuit. What to do? One solution is to hide the coupling as much as possible. The internal circuitry of a chip is extremely complex, but to the outside world its internal circuitry is irrelevant. This approach of hiding coupling as much as possible is called decoupling, which means high cohesion internally and low coupling externally. The logical effect is a layer of abstraction. This allows the outside world to view the chip as a whole, and only needs to care about which interfaces it has. These interfaces are actually coupled, but they are already minimized coupling.
With such a layer of abstraction, engineers can ignore the specific circuit implementation and play with pure logic. This gave birth to programming languages. Therefore, the programming language itself is already highly abstracted based on the decoupling of the underlying hardware. Decoupling in the narrow sense mentioned in software engineering refers to higher-level decoupling based on programming languages ​​(specifically, programs compiled in programming languages) to obtain higher-level abstractions. In this way, by decoupling and abstracting layer by layer, the entire software building including the operating system and application software is built. But tracing back to the source, the origin of the concepts of coupling and decoupling is still at the hardware level, and the software itself is actually an abstraction based on decoupled hardware.
In addition, decoupling is a process, which in software engineering is reflected in code reconstruction based on the principle of high cohesion and low coupling.
I hope my answer will be helpful for you to understand the concepts of coupling and decoupling.

左手右手慢动作

Coupling is not sexual immorality. Even though I write so many words, I don’t like it. Above code:

1. What is coupling?

func foo(){
bar()
}

func bar(){
}

foo uses the bar function, therefore, foo depends on bar. foo is coupled to bar.

2. Package dependencies

If bar is another package, it needs to be imported before use, so we say that foo also depends on the bar package.

3. Simplification: coupling≈dependence

You are too nervous to say "coupling is unnecessary dependencies".

4. Why not just talk about dependence?

Because coupling sounds heavy. For example, the current at one end of the transformer is "coupled" and induces current at the other end - without direct circuit connection - how cool. Back then, computer science was a branch of physics, and such new products had to be contained in an old wine bottle.

5. Why is coupling difficult to understand?

Coupling is easy to understand. Expanded to content coupling, global coupling, coupling, blabla is not easy to understand. Talking about a bunch of cases without giving them is even more complicated.

It’s much better to try to switch to dependencies. In fact http://zh.wikipedia.org/wiki/%E8%80%A6%E5%90%88%E6%80%A7_(%E8%A8%88%E7%AE%97%E6%A9%9F %E7%A7%91%E5%AD%B8) The first three mentioned are all global variable (resource) dependencies.

6. Cases of high coupling problems

Making a database app. See you every day.

Relational database is external coupling. It is also an extension of global variables. I have written CS applications for many years without using an ORM. If you try changing the field names, you will understand the pain of being in a tight coupling - no, a strong coupling relationship.

The field here is bar, and my app is foo.
Coupling theory, what I study is, I changed the bar! change! Change, but there is no need for foo to change too! change! change. The more so, the lower the coupling.

7. Low coupling case

The best one in this regard is win32 api. Versions have changed over the years, but your win32 app can be upgraded naturally without any changes. ox.

PHPzhong

Relatively independent, easy for unit testing, use this as a reference

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template