CSC/ECE 517 Summer 2008/wiki2 6 cc: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 193: Line 193:
     // ...
     // ...
   }
   }
===Advantages and disadvantages===
    Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The "single task mindedness" drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.


==Coupling==
==Coupling==

Revision as of 02:40, 25 June 2008

Cohesion and coupling. 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 is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them.

Cohesion

Cohesion is categorized in “high” and “low” but it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.

Types of Cohesion

The types below are in order from "Highest" to "Lowest"

Functional Cohesion

Functional cohesion describes a module that is designed to perform one and only one task. A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task. The following example illustrates functional cohesion.

 public class Stack 
 {
   public Stack()   
   {
     // implementation
   }
   
   public void push(Object obj)
   {
     // implementation
   }
   
   public Object pop()
   {
     // implementation
   }
   
   public int getSize()
   {
     // implementation
   }
 }
  
Sequential Cohesion

Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation. The following example illustrates sequential cohesion [1].

  class Cube {
      public ArrayList getInfo(){ 
             ArrayList tempList = new ArrayList();
             tempList.add(getArea());
             tempList.add(getVolume());
             return tempList;
      }
      public double getArea(){return 6*side*side;} 
      public double getVolume(){return side*side*side;}
   }
Information cohesion

Information cohesion can do several things with the same data - a class with various methods using same data.

    class Circle {
         double radius;	      
         public double getArea(){return 3.14*radius*radius;}
         public double getDiameter(){return 2 * radius;}
         public double getCircumference(){return 3.14*2*radius;}
    }
Communicational Cohesion

Communicational cohesion describes modules that perform multiple operations on the same input or output data [1]. The following example illustrates communication cohesion [2].

 public class CustomerInformation
 {
   public CustomerInformation(int accountNum)
   {
     // implementation
   }
   
   public String getName()
   {
     // implementation
   }
   
   public float getBalance()
   {
     // implementation
   }
   
   // ...
 }
Procedural Cohesion

Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence. Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation. The following example illustrates procedural cohesion.

 public class Student
 {
   public Student(int studentId)
   {
     // implementation
   }
   
   public void LoadStudent()
   {
     // implementation
   }
   
   public void UpdateGrades(int[] grades)
   {
     // implementation
   }
   
   public void UpdateAttendance(Date[] dates)
   {
     // implementation
   }
   
   public void SaveStudent()
   {
     // implementation
   }
 }
Temporal Cohesion

Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity. The following example illustrates temporal cohesion.

 public class Startup
 {
   public void InitializeLogging()
   {
     // implementation
   }
   
   public void InitializeUI()
   {
     // implementation
   }
   
   public void InitializeDb()
   {
     // implementation
   }
 }
Logical Cohesion

Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different. Typically, these modules accept a control flag which indicates which operation to execute. The following example illustrates logical cohesion [2].

 public class DataStore
 {
   public void SaveData(int destination, byte[] data)
   {
     switch (destination)
     {
       default:
       case 0:
         SaveToDb(data)
         break;
       
       case 1:
         SaveToFile(data)
         break;
       
       case 2:
         SaveToWebService(data)
         break;
     }
   }
   
   protected void SaveToDb(byte[] data)
   {
     // implementation
   }
   
   protected void SaveToFile(byte[] data)
   {
     // implementation
   }
   
   protected void SaveToWebService(byte[] data)
   {
     // implementation
   }
 }
Coincidental Cohesion

Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks. typically used to accomplish several unrelated tasks. The following example illustrates coincidental cohesion [1].

 public static class Math
 {
   public static int Add(int a, int b)
   {
     // implementation
   }
   
   public static int Subtract(int a, int b)
   {
     // implementation
   }
   
   // ...
 }

Advantages and disadvantages

    Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The "single task mindedness" drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.

Coupling

Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.

Types of coupling

The types below are ordered from highest to lowest coupling.

Content coupling

Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module.

   class Circle {
       public double getAreaDifference() { return getArea()-  square.getArea();}
   }
   class Square {
       public String getArea() {  //was double getArea()
            return area;   
       }
   }

Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types.

Common coupling

Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it.

    class Circle{
        String radius;//was double radius;
        public double getArea() {return 3.14*radius*radius;}
        public double getCircumference() {return 2*3.14*radius;}
    }

Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.


Control coupling

Control coupling is one module controlling the logic of another, by passing it information on what to do.

   class FileController {
       public void checkFile(File file)  {
            if (file.size() >5000000)//5 megabytes  
                processFile(true); 
            else processFile(false); 	
        }
       public void processFile(boolean delete) {
            if (delete)
                deleteFile();      	
            else
                closeFile();
       }
     }

This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).

Stamp coupling

Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified.

    class CarInfo {  
         String carType;  
         int numberOfWheels;
         double weight;
     }
    class WeightStation {
      public checkWeight(CarInfo carInfo) {
         if (carInfo.getWeight >4000) 
               System.out.println("car over weight limit");
         else
            System.out.println("car ok");
      }
   }

WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.

Data coupling

Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.

      Public double calculateRoot(int value) {
          return value^(1/2);
      }

Message coupling

This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.

      class superclass {
          public void processData(){ module1.processData();}
       } 
      public Module2 {
          public void doSomething() { superclass.processData();}}


No coupling

Modules do not communicate at all with one another.

Related Concepts

Measuring Cohesion

Measuring Coupling

Demeter's Law

References

  1. http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069
  2. http://www.waysys.com/ws_content_bl_pgssd_ch06.html
  3. http://www.site.uottawa.ca:4321/oose/index.html#cohesion
  4. http://javaboutique.internet.com/tutorials/coupcoh/index-2.html
  5. http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm
  6. http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061