Cohesion

Go to the Wiki Overview

Everyone tells you that you should strive for:

High cohesion, low coupling.

A definition:

Cohesion is about how well elements within a module belong together and serve a common purpose. Coupling is about how much one module depends or interacts with other modules. Thus, cohesion is an intra-module concern whereas coupling cuts across modules [aka inter-module].

(Devopedia)

Cohesion is a property of code that can be measured. It’s like clarity/obscurity, obviousness, or beauty – you need to analyze the code, then you can tell if it’s cohesive, and how. In boxes-and-arrows graphical analysis, it boils down to how many arrows stay inside the group instead of crossing boundaries.

Yourdon’s 6 Levels of Cohesion

Levels of cohesion according to Yourdon, pp. 108-132.1

  1. accidental (coincidental)
    • Reducing code duplication for the sake of reducing code duplication results in “coincidental cohesive modules”. See Don't Repeat Yourself.
    • The code doesn’t have a shared meaning/intent, only superficial similarity.
  2. logical
  3. temporal
  4. communicational
  5. sequential
    • Reactive code is sequentially cohesive: a sequence of operators, from network request to UI update, can encapsulate the steps even more clearly than a regular, imperative function with multiple lines.
  6. functional

I call 1–3 “code-level cohesion”; 4–6 is cohesion reflecting the problem space.

When I write “code-level”, this is meant to invoke something similar to “code smell”: it’s purely derived from looking at the code as code, without interpreting its meaning and how it creates higher-level structures or expresses intent.

SMC Cohesion

Yourdon’s 6 levels are built upon the principles behind “SMC Cohesion”. “SMC” stands for Stevens, Myers, and Constantine.2 Constantine is co-author of Yourdon’s book, so it checks out that the following 7 levels found their way from the SMC paper2 into the Yourdon/Constantine book.

  1. coincidental association
  2. logical association
  3. temporal association
  4. procedural association
  5. communicational association
  6. sequential association
  7. functional association
  1. Edward Yourdon and Larry L. Constantine (1979): Structured design, Englewood Cliffs, N.J.: Prentice-Hall. 

  2. W. P. Stevens, G. J. Myers, and L. L. Constantine (1974): Structured Design, IBM Systems Journal 2, 1974, Vol. 13, S. 115–139.  2