Search This Blog

Monday, November 07, 2011

Coupling and Cohesion in Software and Business

One of the important topics in Object Oriented Programming that is often overlooked or not even considered is that of Coupling and Cohesion. A sound understanding of these concepts can make a huge difference in how you package functionality within your program and how flexible your program can become for enhancements.

When performing source code review, keep coupling and cohesion in mind and ensure that the classes within a package all perform same or closely related activities (high cohesion) and that classes within different packages don't refer each other too much or at least in a well-defined manner (low coupling).

Definitions


Coupling is how inter-dependent two functional components are within your program. High coupling is bad, because if you change one function, you might end up affecting all the dependent functions as well.

Cohesion is how closely the parts within a function work together to make the function as one single, well-defined unit. High cohesion is good, since you can treat the whole function as a black box, thereby abstracting your system for better clarity.

Coupling Types

Type (worst to best) Description
Content/Pathological Coupling When a module uses/alters data in another
Control Coupling 2 modules communicating with a control flag (first tells second what to do via flag)
Common/Global-data Coupling 2 modules communicating via global data
Stamp/Data-structure Coupling Communicating via a data structure passed as a parameter. The data structure holds more information than the recipient needs.
Data Coupling Communicating via parameter passing. The parameters passed are only those that the recipient needs. No data coupling : independent modules.

Cohesion Types

Type (worst to best) Description
Coincidental Cohesion Module elements are unrelated
Logical Cohesion Elements perform similar activities as selected from outside module, i.e. by a flag that selects operation to perform. That is, body of function is one huge if-else/ switch on operation flag
Temporal Cohesion Operations related only by general time performed
Procedural Cohesion Elements involved in different but sequential activities, each on different data (usually could be trivially split into multiple modules along linear sequence boundaries)
Communicational Cohesion Unrelated operations except need same data or input
Sequential Cohesion Operations on same data in significant order; output from one function is input to next (pipeline)
Informational Cohesion A module performs a number of actions, each with its own entry point, with independent code for each action, all performed on the same data structure. Essentially an implementation of an abstract data type
Functional Cohesion All elements contribute to a single, well-defined task, i.e. a function that performs exactly one operation

No comments: