CSC/ECE 517 Summer 2008/wiki2 c6 CohCoupling: Difference between revisions
(131 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
== | ==Problem Definition== | ||
Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling. | |||
=== | ===Introduction=== | ||
Cohesion and | '''[http://en.wikipedia.org/wiki/Cohesion_(computer_science) Cohesion]''' and '''[http://en.wikipedia.org/wiki/Coupling_(computer_science) Coupling]''' are two cornerstones of ''[http://en.wikipedia.org/wiki/Object-Oriented Object-Oriented Programming]''. They sound similar, but have very different meanings. Cohesion is the “act or state of sticking together” or “the logical agreement". It is the basic idea that a ''[http://en.wikipedia.org/wiki/Class_(computer_science) class]'' has a focused set of responsibilities or behaviors from a particular perspective. In contrast to cohesion, Coupling refers to the physical connections between elements of the OO design (eg: the number of collaborations between classes or the number of messages passed between objects) within an OO system. In a simple way, it gives the measure of the interdependence of one module to another. | ||
==Cohesion== | ==Cohesion== | ||
Cohesion is the "glue" that holds a ''[http://en.wikipedia.org/wiki/Module module]'' together. It can be thought of as the type of association among the component elements of a module. Generally, one wants the highest level of cohesion possible. An object with high cohesion is defined for one purpose and it performs only that purpose. An object with low cohesion tends to try to do a lot of different things. For example, if | '''Cohesion''' is the "glue" that holds a ''[http://en.wikipedia.org/wiki/Module module]'' together. It can be thought of as the type of association among the component elements of a module. Cohesion is related to the [http://c2.com/cgi/wiki?SingleResponsibilityPrinciple Single Responsibility Principle]. Generally, one wants the highest level of cohesion possible. An object with high cohesion is defined for one purpose and it performs only that purpose. An object with low cohesion tends to try to do a lot of different things. For example, if there is a Card object which is responsible for drawing itself, sending messages back to the server, and also executing game logic then it has low cohesion because that one class is attempting to do too much. A system can also have low cohesion if too many objects are attempting to do the same thing. For example, if a system has objects to implement a [http://en.wikipedia.org/wiki/Netrunner NetRunner] game and every card has a unique class with a rendering method and that method is nearly identical in all classes, then the system has low cohesion. A good software design is always designed to achieve high cohesion. | ||
An example of a high cohesive EmailMessage class is given below [http://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/]. | An example of a high cohesive EmailMessage class is given below [http://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/]. | ||
class EmailMessage | class EmailMessage | ||
Line 49: | Line 49: | ||
The Login method and username class variable really have nothing to do with the EmailMessage class and its main purpose which makes it a low cohesive class. | The Login method and username class variable really have nothing to do with the EmailMessage class and its main purpose which makes it a low cohesive class. | ||
===Types of Cohesion=== | ===Types of Cohesion [http://www.cs.unc.edu/~stotts/145/cohesion.html]=== | ||
#Coincidental cohesion- A module has | #'''Coincidental cohesion''' (worst)- A module has coincidental cohesion if its elements have no meaningful relationship to one another. It is explained with an example here [http://www.cs.unc.edu/~stotts/145/cohesion.html]. | ||
#Logical cohesion- A module has Logical cohesion when parts of a module are grouped together as they are logically categorized to do the same thing, even if they are different by nature (e.g. grouping all I/O handling routines). [http://www.cs.unc.edu/~stotts/145/logicalcohesion.gif Diagram] | #'''Logical cohesion'''- A module has Logical cohesion when parts of a module are grouped together as they are logically categorized to do the same thing, even if they are different by nature (e.g. grouping all I/O handling routines). [http://www.cs.unc.edu/~stotts/145/logicalcohesion.gif Diagram][[Image:Cohesion.jpg|thumb|300px|Types of Cohesion]] | ||
#Temporal cohesion- A temporally cohesive module is one whose elements are functions that are related in time. It is explained with an example here [http://www.cs.unc.edu/~stotts/145/cohesion.html]. | #'''Temporal cohesion'''- A temporally cohesive module is one whose elements are functions that are related in time. That is operations that are performed to reflect a specific behavior or state. It is explained with an example here [http://www.cs.unc.edu/~stotts/145/cohesion.html]. | ||
#Procedural cohesion-A procedurally cohesive module is one whose elements are involved in different activities, but the activities are sequential.[http://www.cs.unc.edu/~stotts/145/proceduralcohesion.gif Diagram] | #'''Procedural cohesion'''-A procedurally cohesive module is one whose elements are involved in different activities, but the activities are sequential.[http://www.cs.unc.edu/~stotts/145/proceduralcohesion.gif Diagram] | ||
#Communicational cohesion- A communicationally cohesive module is one whose elements perform different functions, but each function references the same input information or output.[http://www.cs.unc.edu/~stotts/145/communicationalcohesion.gif Diagram] | #'''Communicational cohesion'''- A communicationally cohesive module is one whose elements perform different functions, but each function references the same input information or output.[http://www.cs.unc.edu/~stotts/145/communicationalcohesion.gif Diagram] | ||
#Sequential cohesion- A sequentially cohesive module is one whose functions are related such that output data from one function serves as input data to the next function. [http://www.cs.unc.edu/~stotts/145/sequentialcohesion.gif Diagram] | #'''Sequential cohesion'''- A sequentially cohesive module is one whose functions are related such that output data from one function serves as input data to the next function. The intent is to implement a sequence of operations [http://www.cs.unc.edu/~stotts/145/sequentialcohesion.gif Diagram]. | ||
#Functional cohesion- A functionally cohesive module is one in which all of the elements | #'''Functional cohesion''' (best)- A functionally cohesive module is one in which all of the elements in a module performs one and only one computation and then returns a result. Object-oriented languages tend to support this level of cohesion better than earlier languages do. | ||
Studies indicate that the first two types of cohesion are inferior, communicational and sequential cohesion are very good and functional cohesion is superior. A detailed description of each cohesion type is given here [http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069]. | |||
===Measurement of cohesion=== | |||
A high degree of cohesion is attained by: | |||
*Including all the relevant elements of the object together in one class instead of chaining through invisible objects (like automobileTag).For example, in the given class Person, the elements automobile tag and automobile year are not directly relevant to a person. So, we can create a new class 'Car' and include it as an element in class 'Person'. | |||
class Person { class Person { | |||
String name; String name; | |||
String automobileTag; Car automobile; | |||
String automobileYear; ----> } | |||
} | |||
class Car { | |||
String tag; | |||
int year; | |||
} | |||
*Include all the necessary elements in the object, so that the elements presence would model the object accurately. For example, in class 'TriagePatient', it is not necessary to include the favorite TV show. One way of including the rarely used attributes (like favoriteTVshow) conditions is to create a subclass. | |||
class TriagePatient { class TriagePatient { | |||
Boolean inShock? Boolean inShock? | |||
String bloodType; String bloodType; | |||
String favoriteTVshow; -----> } | |||
} | |||
class RecoveringPatient { | |||
String favoriteTVshow; | |||
} | |||
*Ensure that all the necessary elements are present in the class to achieve completeness. For example, in a class like 'Stack', there should be a mechanism to push and pop elements to complete the stack. Some relevant elements may get omitted due to complexity. Knowing what to leave out is part of abstraction. | |||
class Stack { class Stack { | |||
int size; -----> int size; | |||
Object elems[]; Object elems[]; | |||
push(elem) {...} push(elem) {...} | |||
} pop() { } | |||
} | |||
===Advantages=== | ===Advantages of high cohesion=== | ||
* Cohesion is the idea that a given thing (be it a system, and object,or a method) does a single, clearly definable thing. This has the benefit of making your code easier to follow | * Cohesion is the idea that a given thing (be it a system, and object,or a method) does a single, clearly definable thing. This has the benefit of making your code easier to follow. | ||
* Promotes code reuse, since small atomic blocks are easier to reuse then larger blocks. | * Promotes code reuse, since small atomic blocks are easier to reuse then larger blocks. | ||
* | * High cohesion makes it easier to replace a module by another one that provides same functionality. | ||
* | * High cohesion reduces complexity of the system, and hence increase the application's reliability. | ||
* If the module is highly cohesive, the software is more readable and maintainable. | |||
* Communication between developers is easier. | |||
== Coupling == | == Coupling == | ||
Coupling is a qualitative measure of the degree to which the classes, modules or subsystems are connected to one another. It can be defined as the amount of interaction of one object with another object, or one module with another module. For a good software design, it is always advisable to minimize coupling. Low coupling does not mean no coupling, the goal is reduction rather than elimination of coupling. A system with no coupling is, by definition, not a system. Low coupling indicates that each object or module performs independent tasks. In general, low coupling can be well explained by ''[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter]''. It states that classes within a module or subsystem should have only limited knowledge of classes in other modules or subsystems. In simple terms, 'Law of Demeter' says "Each unit should only talk to its friends; don't talk to strangers". Strong coupling means that one object or module is dependent on other object or module to perform an operation or task. It simply means that the object or module is strongly coupled with the implementation details of another object or module. | '''Coupling''' is a qualitative measure of the degree to which the classes, modules or subsystems are connected to one another. It can be defined as the amount of interaction of one object with another object, or one module with another module. For a good software design, it is always advisable to minimize coupling. Low coupling does not mean no coupling, the goal is reduction rather than elimination of coupling. A system with no coupling is, by definition, not a system. Low coupling indicates that each object or module performs independent tasks. In general, low coupling can be well explained by ''[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter]''. It states that classes within a module or subsystem should have only limited knowledge of classes in other modules or subsystems. In simple terms, 'Law of Demeter' says "Each unit should only talk to its friends; don't talk to strangers". Strong coupling means that one object or module is dependent on other object or module to perform an operation or task. It simply means that the object or module is strongly coupled with the implementation details of another object or module. With low coupling, a change in one module will not require a change in the implementation of another module. | ||
An example of a two highly coupled objects an iPod object and a Song object is given below [http://benrobb.com/2007/01/20/coupling-vs-cohesion/]. Song class might look something like this | An example of a two highly coupled objects an iPod object and a Song object is given below [http://benrobb.com/2007/01/20/coupling-vs-cohesion/]. Song class might look something like this in Ruby style. | ||
class Song | class Song | ||
def do(action) | def do(action) | ||
Line 80: | Line 117: | ||
end | end | ||
end | end | ||
In the above program, programmer who wants to interface the iPod object with the Song object is now dependent on the special meaning of 1, 2, & 3 to use the Song object correctly. The iPod object and the Song object are highly coupled. We can implement these objects in another way which | In the above program, programmer who wants to interface the iPod object with the Song object is now dependent on the special meaning of 1, 2, & 3 to use the Song object correctly. The iPod object and the Song object are highly coupled. We can implement these objects in another way which makes these objects more cohesive is given below. | ||
class Song | class Song | ||
def new(path_to_song) | def new(path_to_song) | ||
Line 98: | Line 135: | ||
With the above code, other objects that wish to interact with it can do so in a uniform way regardless of how the Song object is implemented on the backend. They just know that Song object does what it is supposed to do. | With the above code, other objects that wish to interact with it can do so in a uniform way regardless of how the Song object is implemented on the backend. They just know that Song object does what it is supposed to do. | ||
===Types of Coupling=== | ===Types of Coupling [http://www.cs.unc.edu/~stotts/145/coupling.html]=== | ||
#No Direct Coupling - These are independent modules and so are not really components of a single system. | #'''No Direct Coupling''' (low) - These are independent modules and so are not really components of a single system. | ||
#Data Coupling - Two modules are data coupled if they communicate by passing parameters or data arguments. Increase in data coupling results in increased complexity of interfaces, because the bandwidth of communication between classes increase [http://www.cs.unc.edu/~stotts/145/datacoupled.gif Diagram]. | #'''Data Coupling''' - Two modules are data coupled if they communicate by passing parameters or data arguments. Increase in data coupling results in increased complexity of interfaces, because the bandwidth of communication between classes increase [http://www.cs.unc.edu/~stotts/145/datacoupled.gif Diagram].[[Image:Coupling.jpg|thumb|300px|Types of Coupling]]. | ||
#Stamp Coupling - Two modules are stamp coupled if they communicate via a passed data structure that contains more information than necessary for them to perform their functions [http://www.cs.unc.edu/~stotts/145/stampcoupled.gif Diagram] | #'''Stamp Coupling''' - Two modules are stamp coupled if they communicate via a passed data structure that contains more information than necessary for them to perform their functions. For example, class B is declared as atype for an argument of an operation of class A. Therefore, modifying the system could be complicated as now class B is a part of the definition of class A. [http://www.cs.unc.edu/~stotts/145/stampcoupled.gif Diagram] | ||
#Control Coupling - Two modules are control coupled if they communicate using at least one "control flag" [http://www.cs.unc.edu/~stotts/145/controlcoupled.gif Diagram]. | #'''Control Coupling''' - Two modules are control coupled if they communicate using at least one "control flag". For example, operation X() invokes operation Y() and passes control flag to Y. In this case, changing code of operation Y may require change in flag value passed by X. [http://www.cs.unc.edu/~stotts/145/controlcoupled.gif Diagram]. | ||
#Common Coupling - Two modules are common coupled if they both share the same global data area. It is useful to establish values that are | #'''Common Coupling''' - Two modules are common coupled if they both share the same global data area. It is useful to establish values that are common to entire application, however, it can lead to uncontrolled error propagation that can be difficult to trace. [http://www.cs.unc.edu/~stotts/145/commoncoupled.gif Diagram] | ||
#Content coupling - Content coupling is when one module modifies or relies on the internal workings of another module (e.g. accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module. This violates information hiding - a basic object oriented design concept. | #'''Content coupling''' (high)- Content coupling is when one module modifies or relies on the internal workings of another module (e.g. accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module. This violates information hiding - a basic object oriented design concept. | ||
In object-oriented programming, ''[http://www.economicexpert.com/a/Subclass:coupling.html Subclass coupling]'' describes a special type of coupling between a parent class and its child. It describes the relationship between a class and its parent. The class is connected to its parent, but the parent isn't connected to the child. | In object-oriented programming, ''[http://www.economicexpert.com/a/Subclass:coupling.html Subclass coupling]'' describes a special type of coupling between a parent class and its child. It describes the relationship between a class and its parent. The class is connected to its parent, but the parent isn't connected to the child. | ||
===To achieve low coupling=== | ===To achieve low coupling=== | ||
1. Strive for low message coupling. | 1. Strive for low message coupling. It can be achieved in the following ways - | ||
* | * Number of messages passed between objects can be reduced. | ||
* | * Messages can be simplified using few parameters. | ||
* Avoid requiring multi-message sequences. | * Avoid requiring multi-message sequences. | ||
Line 119: | Line 157: | ||
car.turnKeyInIgnition(); | car.turnKeyInIgnition(); | ||
2. Strive for low association coupling. | 2. Strive for low ''[http://en.wikipedia.org/wiki/Association_(object-oriented_programming) association]'' coupling. It can be achieved by - | ||
* Reduce extent to which objects depend on the internal structure of each other. | * Reduce extent to which objects depend on the internal structure of each other. | ||
* Reduce the use of | * Reduce the use of ''[http://www.science.uva.nl/ict/ossdocs/java/tutorial/java/javaOO/subclasses.html superclasses]'' instance variables by ''[http://www.science.uva.nl/ict/ossdocs/java/tutorial/java/javaOO/subclasses.html subclasses]'' (strong form of the Law of Demeter). | ||
class Person { | class Person { | ||
String first, last; class Doctor : Person { | String first, last; class Doctor : Person { | ||
Line 134: | Line 172: | ||
} | } | ||
3. Strive for moderate inheritance coupling. | 3. Strive for moderate ''[http://en.wikipedia.org/wiki/Inheritance_(computer_science) inheritance]'' coupling. It can be achieved in the following ways - | ||
* Abstract so that subclasses depend on the methods (but not the structure!) of their superclasses. | * Abstract so that subclasses depend on the methods (but not the structure!) of their superclasses. | ||
* Use or refine as many of superclass' operations as possible in the child classes. | * Use or refine as many of superclass' operations as possible in the child classes. | ||
class Person { | class Person { | ||
Line 150: | Line 188: | ||
} | } | ||
=== | === Disadvantages of high coupling=== | ||
* Coupling | * Decreases the flexibility of the application software. Developers / maintenance programmers need to understand potentially the whole system to be able to safely modify a single component. | ||
* Object interaction complexity associated with coupling can lead to increased error generation during development. | |||
* Decreases the scalability of the application software. Changing requirements in one part of software will potentially require wide ranging changes in the entire application. | |||
* Decreases the maintainability of the application software. More thought need to go into choices at the beginning of the lifetime of a software system in order to attempt to predict the long term requirements of the system because changes are more expensive. | |||
* Testability is likely to degrade with a more highly coupled system of objects. | |||
== Cohesion and Coupling Examples == | |||
As the popular proverb says " A picture is worth a thousand words ", we will try to represent cohesion and coupling in terms of [http://www.hypernews.org/~liberte/computing/visual.html visual programming metaphors]. Observe [http://www.kellen.net/Coupling%20and%20Cohesion.htm Figures] 1 and 2.[[Image:LooseCoupledHighCohesion.jpg |thumb|250px|Figure1: Loosely Coupled & Highly Cohesive]] What can one say about the two diagrams? Which one is easy to understand, remember and modify? Obviously the answer would be Figure 1. This is exactly why it is recommended to have high cohesion and loose coupling in design or implementation of a software application. The two figures gives a clear visualization of the underlying concepts of coupling and cohesion. [[Image:HighCoupledLooseCohesion.jpg |thumb|250px|Figure2: Highly Coupled & Loosely Cohesive]]. | |||
'''In General''' | |||
Let us take a look at some simple real life examples to understand the relation between these two terms. | |||
Example 1. Project team - If we assume that a certain project has 20 people working on it, the possible communication channels would be around 400. The team would be very inefficient with high communication overhead. It can be viewed as an example of tight coupling. Therefore, in any team, certain roles and responsibilities are formally assigned to team member, to enhance productivity of the team with smooth coordination. Well defined roles of a team member can be viewed as high cohesion, and establishing communication channels (like defining hierarchy or reporting structure) can be viewed as low coupling. This is a very practical example of low coupling and high cohesion comes. | |||
Example 2. Car - Let us consider another real life example of a car. It has the engine, tire, steering wheel, gear box, brakes etc. Each component of the car performs a given set of functions. Therefore, if the car breaks down, the problem can be analyzed and only certain part needs to be repaired. This can be considered as high cohesion, as each component focuses on the assigned task. At the same time, in order drive the car, all these parts need to interact with each other. This can be viewed as coupling. | |||
Example 3. Child and Parent relationship - | |||
Cohesion and coupling can be well expressed using the analogy of a parent child relationship. The child inherits characteristics of its parents. This can be viewed as coupling. At the same time, there is no coupling in the siblings. | |||
'''In Object Oriented terms''' | |||
[http://dotnetslackers.com/articles/csharp/PolymorphismEncapsulation.aspx Polymorphism and encapsulation] are two major design principles of object oriented programming. In object oriented terms, we can say that, the main vehicle of coupling is polymorphism [http://vista.intersystems.com/csp/docbook/DocBook.UI.Page.cls?KEY=TOBJ_PolymorphismAndLooseCoupling] and the main vehicle of cohesion is encapsulation. More explanation is provided in cohesion and coupling. | |||
In order to achieve modularity, we need to have low coupling and high cohesion.“[http://www-cse.ucsd.edu/users/wgg/CSE131B/Design/node1.html Modularity] is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.” [http://en.wikipedia.org/wiki/Grady_Booch Booch 1994] | |||
Principle: Modularity = Low Coupling + High Cohesion | |||
It can be simply understood as, breaking something complex into set of manageable pieces. Consider the example of order processing system. If we decide to write entire software in only one program, it will become lengthy, unmanageable, complicated and hard to debug. Instead, we can divide it into modules or subsystems like order entry, order processing, billing and complaints. | |||
== | ==Conclusion== | ||
Code that is easy to maintain and reusable can be attained by sticking to loose coupling and high cohesion in objects. The concept of coupling is usually related to the concept of cohesion so low coupling facilitates high cohesion, and vice versa. It is difficult to obtain perfect high cohesion and low coupling throughout the program. Once all the unitary functions that depend only on their inputs are written, a bit of less cohesive and more coupled code is required to glue them together into a working program. But, there are also times where tight coupling is desirable. Tighter the coupling, it improves performance as it reduces the cost of interfaces. So, tight coupling is important when one process is very stable and wants maximum performance and loose coupling comes into play when flexibility is required rather than stability. There can also be situations where even though high cohesion is attained, tight coupling is also present. This means though it may be logically laid out, it's tough to change because of tight interdependencies which is pretty bad. The other kind of bad software is eventhough the module is loosely coupled but it may lack cohesion. That means that there are few explicit | |||
interdependencies between modules, but none of the modules are necessarily authoritative about any particular aspect of the system. This in turn | |||
results in a scattergun approach to ongoing system evolution as even minor changes ripple through multiple components or systems. As to conclude, the | |||
objective of a good software should be to achieve '''high cohesion''' and '''low coupling'''. | |||
==See Also== | ==See Also== | ||
Line 176: | Line 231: | ||
*[http://www.barneyb.com/barneyblog/index.php?s=cohesion Blog on Cohesion and coupling] | *[http://www.barneyb.com/barneyblog/index.php?s=cohesion Blog on Cohesion and coupling] | ||
*[http://www.slideshare.net/phananhvu/oop-2/ Pdf on Cohesion and Coupling] | *[http://www.slideshare.net/phananhvu/oop-2/ Pdf on Cohesion and Coupling] | ||
*[http://www.hokstad.com/why-coupling-is-always-bad-cohesion-vs-coupling.html Why coupling is always bad / Cohesion vs. coupling] | *[http://www.hokstad.com/why-coupling-is-always-bad-cohesion-vs-coupling.html Why coupling is always bad / Cohesion vs. coupling] | ||
*[http://www.theregister.co.uk/2006/08/31/cohesion_coupling/ Up with cohesion, down with coupling] | |||
*[http://www.ebizq.net/topics/eai/features/4688.html?&pp=1 Coupling Versus Cohesion: When to Leverage Services] | |||
*[http://www.cs.colorado.edu/~kena/classes/5828/s99/comments/nathanryan/01-29-1999.html Cohesion and coupling example] | |||
*[http://class.ee.iastate.edu/berleant/home/Courses/SoftwareEngineering/CprE486fall2004/designModularity.htm What makes a module a good module?] | |||
*[http://www.amazon.com/gp/reader/007301933X/ref=sib_dp_pt#reader-link Software Engineering: A Practitioner's Approach ] | |||
*[http://leansoftwareengineering.com/2007/08/08/what-is-coupling-really/ What is coupling, really?] | |||
*[http://www.infoq.com/news/2008/04/soa-cohesion Is Cohesion Important for SOA?] | |||
*[http://www.brianlegros.com/blog/2007/07/23/architectual-styles-part-two-cohesion-and-coupling/ Architectual Styles- Cohesion and Coupling] | |||
*[http://www.eli.sdsu.edu/courses/spring01/cs635/notes/module/module.html Module Coupling & Cohesion ] | |||
[http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Summer_2008/wiki2_Assignment Back to the Assignment Page] |
Latest revision as of 14:30, 7 July 2008
Problem Definition
Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.
Introduction
Cohesion and Coupling are two cornerstones of Object-Oriented Programming. They sound similar, but have very different meanings. Cohesion is the “act or state of sticking together” or “the logical agreement". It is the basic idea that a class has a focused set of responsibilities or behaviors from a particular perspective. In contrast to cohesion, Coupling refers to the physical connections between elements of the OO design (eg: the number of collaborations between classes or the number of messages passed between objects) within an OO system. In a simple way, it gives the measure of the interdependence of one module to another.
Cohesion
Cohesion is the "glue" that holds a module together. It can be thought of as the type of association among the component elements of a module. Cohesion is related to the Single Responsibility Principle. Generally, one wants the highest level of cohesion possible. An object with high cohesion is defined for one purpose and it performs only that purpose. An object with low cohesion tends to try to do a lot of different things. For example, if there is a Card object which is responsible for drawing itself, sending messages back to the server, and also executing game logic then it has low cohesion because that one class is attempting to do too much. A system can also have low cohesion if too many objects are attempting to do the same thing. For example, if a system has objects to implement a NetRunner game and every card has a unique class with a rendering method and that method is nearly identical in all classes, then the system has low cohesion. A good software design is always designed to achieve high cohesion. An example of a high cohesive EmailMessage class is given below [1].
class EmailMessage { private string sendTo; private string subject; private string message; public EmailMessage(string to, string subject, string message) { this.sendTo = to; this.subject = subject; this.message = message; } public void SendMessage() { // send message using sendTo, subject and message } }
The above class was originally designed to send an email message. Suppose if it is modified in the future in a way that the user needed to be logged in to send an email which is implemented by adding a Login method to the EmailMessage class.
class EmailMessage { private string sendTo; private string subject; private string message; private string username; public EmailMessage(string to, string subject, string message) { this.sendTo = to; this.subject = subject; this.message = message; } public void SendMessage() { // send message using sendTo, subject and message } public void Login(string username, string password) { this.username = username; // code to login } }
The Login method and username class variable really have nothing to do with the EmailMessage class and its main purpose which makes it a low cohesive class.
Types of Cohesion [2]
- Coincidental cohesion (worst)- A module has coincidental cohesion if its elements have no meaningful relationship to one another. It is explained with an example here [3].
- Logical cohesion- A module has Logical cohesion when parts of a module are grouped together as they are logically categorized to do the same thing, even if they are different by nature (e.g. grouping all I/O handling routines). Diagram
- Temporal cohesion- A temporally cohesive module is one whose elements are functions that are related in time. That is operations that are performed to reflect a specific behavior or state. It is explained with an example here [4].
- Procedural cohesion-A procedurally cohesive module is one whose elements are involved in different activities, but the activities are sequential.Diagram
- Communicational cohesion- A communicationally cohesive module is one whose elements perform different functions, but each function references the same input information or output.Diagram
- Sequential cohesion- A sequentially cohesive module is one whose functions are related such that output data from one function serves as input data to the next function. The intent is to implement a sequence of operations Diagram.
- Functional cohesion (best)- A functionally cohesive module is one in which all of the elements in a module performs one and only one computation and then returns a result. Object-oriented languages tend to support this level of cohesion better than earlier languages do.
Studies indicate that the first two types of cohesion are inferior, communicational and sequential cohesion are very good and functional cohesion is superior. A detailed description of each cohesion type is given here [5].
Measurement of cohesion
A high degree of cohesion is attained by:
- Including all the relevant elements of the object together in one class instead of chaining through invisible objects (like automobileTag).For example, in the given class Person, the elements automobile tag and automobile year are not directly relevant to a person. So, we can create a new class 'Car' and include it as an element in class 'Person'.
class Person { class Person { String name; String name; String automobileTag; Car automobile; String automobileYear; ----> } } class Car { String tag; int year; }
- Include all the necessary elements in the object, so that the elements presence would model the object accurately. For example, in class 'TriagePatient', it is not necessary to include the favorite TV show. One way of including the rarely used attributes (like favoriteTVshow) conditions is to create a subclass.
class TriagePatient { class TriagePatient { Boolean inShock? Boolean inShock? String bloodType; String bloodType; String favoriteTVshow; -----> } } class RecoveringPatient { String favoriteTVshow; }
- Ensure that all the necessary elements are present in the class to achieve completeness. For example, in a class like 'Stack', there should be a mechanism to push and pop elements to complete the stack. Some relevant elements may get omitted due to complexity. Knowing what to leave out is part of abstraction.
class Stack { class Stack { int size; -----> int size; Object elems[]; Object elems[]; push(elem) {...} push(elem) {...} } pop() { } }
Advantages of high cohesion
- Cohesion is the idea that a given thing (be it a system, and object,or a method) does a single, clearly definable thing. This has the benefit of making your code easier to follow.
- Promotes code reuse, since small atomic blocks are easier to reuse then larger blocks.
- High cohesion makes it easier to replace a module by another one that provides same functionality.
- High cohesion reduces complexity of the system, and hence increase the application's reliability.
- If the module is highly cohesive, the software is more readable and maintainable.
- Communication between developers is easier.
Coupling
Coupling is a qualitative measure of the degree to which the classes, modules or subsystems are connected to one another. It can be defined as the amount of interaction of one object with another object, or one module with another module. For a good software design, it is always advisable to minimize coupling. Low coupling does not mean no coupling, the goal is reduction rather than elimination of coupling. A system with no coupling is, by definition, not a system. Low coupling indicates that each object or module performs independent tasks. In general, low coupling can be well explained by Law of demeter. It states that classes within a module or subsystem should have only limited knowledge of classes in other modules or subsystems. In simple terms, 'Law of Demeter' says "Each unit should only talk to its friends; don't talk to strangers". Strong coupling means that one object or module is dependent on other object or module to perform an operation or task. It simply means that the object or module is strongly coupled with the implementation details of another object or module. With low coupling, a change in one module will not require a change in the implementation of another module.
An example of a two highly coupled objects an iPod object and a Song object is given below [6]. Song class might look something like this in Ruby style.
class Song def do(action) if action == 1 # code to play song… elsif action == 2 # code to pause elsif action == 3 # code to skip endif end end
In the above program, programmer who wants to interface the iPod object with the Song object is now dependent on the special meaning of 1, 2, & 3 to use the Song object correctly. The iPod object and the Song object are highly coupled. We can implement these objects in another way which makes these objects more cohesive is given below.
class Song def new(path_to_song) #code to get the song from the filesystem end def self.play #code to play song end def self.pause # code to pause song end end #This would allow the iPod object to call currentSong = Song.new(”/home/user/Music/1812_Overture.mp3″) currentSong.play currentSong.pause
With the above code, other objects that wish to interact with it can do so in a uniform way regardless of how the Song object is implemented on the backend. They just know that Song object does what it is supposed to do.
Types of Coupling [7]
- No Direct Coupling (low) - These are independent modules and so are not really components of a single system.
- Data Coupling - Two modules are data coupled if they communicate by passing parameters or data arguments. Increase in data coupling results in increased complexity of interfaces, because the bandwidth of communication between classes increase Diagram..
- Stamp Coupling - Two modules are stamp coupled if they communicate via a passed data structure that contains more information than necessary for them to perform their functions. For example, class B is declared as atype for an argument of an operation of class A. Therefore, modifying the system could be complicated as now class B is a part of the definition of class A. Diagram
- Control Coupling - Two modules are control coupled if they communicate using at least one "control flag". For example, operation X() invokes operation Y() and passes control flag to Y. In this case, changing code of operation Y may require change in flag value passed by X. Diagram.
- Common Coupling - Two modules are common coupled if they both share the same global data area. It is useful to establish values that are common to entire application, however, it can lead to uncontrolled error propagation that can be difficult to trace. Diagram
- Content coupling (high)- Content coupling is when one module modifies or relies on the internal workings of another module (e.g. accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module. This violates information hiding - a basic object oriented design concept.
In object-oriented programming, Subclass coupling describes a special type of coupling between a parent class and its child. It describes the relationship between a class and its parent. The class is connected to its parent, but the parent isn't connected to the child.
To achieve low coupling
1. Strive for low message coupling. It can be achieved in the following ways -
- Number of messages passed between objects can be reduced.
- Messages can be simplified using few parameters.
- Avoid requiring multi-message sequences.
car.pushPedal(CLUTCH); car.shiftToGear(PARK); ---> car.start(carKey); car.insertKey(carKey); car.pushPedal(GAS); car.turnKeyInIgnition();
2. Strive for low association coupling. It can be achieved by -
- Reduce extent to which objects depend on the internal structure of each other.
- Reduce the use of superclasses instance variables by subclasses (strong form of the Law of Demeter).
class Person { String first, last; class Doctor : Person { getName { first + last } getName { } ^ -----> "Dr" + Person::getName(); | } | } class Doctor : Person { getName { "Dr" + first + last; } }
3. Strive for moderate inheritance coupling. It can be achieved in the following ways -
- Abstract so that subclasses depend on the methods (but not the structure!) of their superclasses.
- Use or refine as many of superclass' operations as possible in the child classes.
class Person { hello { print "Hi!" class Doctor : Person { } greetings { } ^ ----> hello(); | } | } class Doctor : Person { greetings { print "Hi!"; } }
Disadvantages of high coupling
- Decreases the flexibility of the application software. Developers / maintenance programmers need to understand potentially the whole system to be able to safely modify a single component.
- Object interaction complexity associated with coupling can lead to increased error generation during development.
- Decreases the scalability of the application software. Changing requirements in one part of software will potentially require wide ranging changes in the entire application.
- Decreases the maintainability of the application software. More thought need to go into choices at the beginning of the lifetime of a software system in order to attempt to predict the long term requirements of the system because changes are more expensive.
- Testability is likely to degrade with a more highly coupled system of objects.
Cohesion and Coupling Examples
As the popular proverb says " A picture is worth a thousand words ", we will try to represent cohesion and coupling in terms of visual programming metaphors. Observe Figures 1 and 2.
What can one say about the two diagrams? Which one is easy to understand, remember and modify? Obviously the answer would be Figure 1. This is exactly why it is recommended to have high cohesion and loose coupling in design or implementation of a software application. The two figures gives a clear visualization of the underlying concepts of coupling and cohesion.
.
In General
Let us take a look at some simple real life examples to understand the relation between these two terms.
Example 1. Project team - If we assume that a certain project has 20 people working on it, the possible communication channels would be around 400. The team would be very inefficient with high communication overhead. It can be viewed as an example of tight coupling. Therefore, in any team, certain roles and responsibilities are formally assigned to team member, to enhance productivity of the team with smooth coordination. Well defined roles of a team member can be viewed as high cohesion, and establishing communication channels (like defining hierarchy or reporting structure) can be viewed as low coupling. This is a very practical example of low coupling and high cohesion comes.
Example 2. Car - Let us consider another real life example of a car. It has the engine, tire, steering wheel, gear box, brakes etc. Each component of the car performs a given set of functions. Therefore, if the car breaks down, the problem can be analyzed and only certain part needs to be repaired. This can be considered as high cohesion, as each component focuses on the assigned task. At the same time, in order drive the car, all these parts need to interact with each other. This can be viewed as coupling.
Example 3. Child and Parent relationship - Cohesion and coupling can be well expressed using the analogy of a parent child relationship. The child inherits characteristics of its parents. This can be viewed as coupling. At the same time, there is no coupling in the siblings.
In Object Oriented terms
Polymorphism and encapsulation are two major design principles of object oriented programming. In object oriented terms, we can say that, the main vehicle of coupling is polymorphism [8] and the main vehicle of cohesion is encapsulation. More explanation is provided in cohesion and coupling.
In order to achieve modularity, we need to have low coupling and high cohesion.“Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.” Booch 1994
Principle: Modularity = Low Coupling + High Cohesion
It can be simply understood as, breaking something complex into set of manageable pieces. Consider the example of order processing system. If we decide to write entire software in only one program, it will become lengthy, unmanageable, complicated and hard to debug. Instead, we can divide it into modules or subsystems like order entry, order processing, billing and complaints.
Conclusion
Code that is easy to maintain and reusable can be attained by sticking to loose coupling and high cohesion in objects. The concept of coupling is usually related to the concept of cohesion so low coupling facilitates high cohesion, and vice versa. It is difficult to obtain perfect high cohesion and low coupling throughout the program. Once all the unitary functions that depend only on their inputs are written, a bit of less cohesive and more coupled code is required to glue them together into a working program. But, there are also times where tight coupling is desirable. Tighter the coupling, it improves performance as it reduces the cost of interfaces. So, tight coupling is important when one process is very stable and wants maximum performance and loose coupling comes into play when flexibility is required rather than stability. There can also be situations where even though high cohesion is attained, tight coupling is also present. This means though it may be logically laid out, it's tough to change because of tight interdependencies which is pretty bad. The other kind of bad software is eventhough the module is loosely coupled but it may lack cohesion. That means that there are few explicit interdependencies between modules, but none of the modules are necessarily authoritative about any particular aspect of the system. This in turn results in a scattergun approach to ongoing system evolution as even minor changes ripple through multiple components or systems. As to conclude, the objective of a good software should be to achieve high cohesion and low coupling.
See Also
External links
- Blog on Cohesion and coupling
- Pdf on Cohesion and Coupling
- Why coupling is always bad / Cohesion vs. coupling
- Up with cohesion, down with coupling
- Coupling Versus Cohesion: When to Leverage Services
- Cohesion and coupling example
- What makes a module a good module?
- Software Engineering: A Practitioner's Approach
- What is coupling, really?
- Is Cohesion Important for SOA?
- Architectual Styles- Cohesion and Coupling
- Module Coupling & Cohesion