耦合与凝聚力

我试图将耦合和内聚的概念归结为一个简洁的定义。有没有人能给我一个简短易懂的解释(比维基百科上 给你给你的定义要短) ?它们是如何互动的?

谢谢。

有人能举个简短的例子吗?

45764 次浏览

Coupling - A measure of how much a module (package, class, method) relies on other modules. It is desirable to reduce coupling, or reduce the amount that a given module relies on the other modules of a system.

Cohesion - A measure of how closely related the members (classes, methods, functionality within a method) of a module are to the other members of the same module. It is desirable to increase cohesion as that indicates that a module has a very specific task and does only that task.

"Coupling is a measure of interdependencies between modules, which should be minimized" "cohesion, a quality to be maximized, focuses on the relationships between the activities performed by each module."

quoted from this paper: http://steve.vinoski.net/pdf/IEEE-Old_Measures_for_New_Services.pdf

A quick-and-dirty way to measure coupling is to measure your import (or similar) statements.

Coupling

  • Loose: You and the guy at the convenience store. You communicate through a well-defined protocol to achieve your respective goals - you pay money, he lets you walk out with the bag of Cheetos. Either one of you can be replaced without disrupting the system.

  • Tight: You and your wife.

Cohesion

  • Low: The convenience store. You go there for everything from gas to milk to ATM banking. Products and services have little in common, and the convenience of having them all in one place may not be enough to offset the resulting increase in cost and decrease in quality.

  • High: The cheese store. They sell cheese. Nothing else. Can't beat 'em when it comes to cheese though.

One of the best comprehensive discussions of software design concepts related to OO (including these ones) is Bertrand Meyer's Object Oriented Software Construction.

Regarding 'coupling', he gives his Weak Coupling / Small Interfaces rule as follows:

If two modules communicate, they should exchange as little information as possible.

Meyer's material related to cohesion isn't ever boiled down to a single pithy statement, but I think this sentence from Steve McConnell's Code Complete sums it up pretty well:

Cohesion refers to how closely all the routines in a class or all the code in a routine support a central purpose

Coupling means dependency on others.
Cohesion means completeness with itself.