Engineering Notes

Written by Mohamed Hafez software engineer @aqarmap.com

Cohesion In Object Oriented Design

Posted at — Oct 12, 2019

Our main topic for this series is how to write good software with this quote

Good software is highly cohesive and loosely coupled (Separation Of Concern).

What is the benefit from writing a good software?

Writing maintainable, testable and readable code helps increase productivity for us as developers. Having highly maintainable code makes it easier to design new features and write code. Modular, component-based, and layered code increase productivity and reduce risk and cost when making changes.

What is Cohesion?

In software design, it is the degree to which the elements of a certain class belong together.

What is Cohesion types?

  1. Functional cohesion (best): This is high cohesion and that means the class should be self-contained and with a single purpose. In other words the class should do one thing and one thing very well. High cohesion is closely related to Single responsibility principle.

High cohesion

Examples:

The benefits of high cohesion are:


  1. Sequential cohesion: is when parts of a class are grouped because the output from one part is the input to another part like an assembly line (e.g., a function which reads data from a file and processes the data).

High cohesion


3- Communicational/informational cohesion: is when parts of a module are grouped because they operate on the same data.

communicational/informational cohesion

communicational/informational cohesion

Examples:

$db->Update(record)
record->Print()

Why is communicational cohesion bad?


4- Procedural cohesion: is when parts of a module are grouped because they always follow a certain sequence of execution (e.g., a function which checks file permissions and then opens the file).

procedural cohesion

procedural cohesion

Examples:

$userInput->All()
$validator->Validate($userInput)
$db->Store()

Why is procedural cohesion bad?


5- Temporal cohesion: is when parts of a module are grouped to perform a series of actions related in time (e.g., a function which is called after catching an exception which closes open files, creates an error log, and notifies the user).

Temporal cohesion

Why is procedural cohesion bad?


6- Logical cohesion: is when parts of a module are grouped because they are logically categorized to do the same thing even though they are different by nature (e.g., grouping all mouse and keyboard input handling routines).

Why is logical cohesion bad?


7- Coincidental cohesion (worst): is when parts of a module are grouped arbitrarily; the only relationship between each part is that they have been grouped together (e.g., a “Utilities” class).

Low cohesion

How to fix the coincidental cohesion?


Recap

flowchart for cohesion

good and bad cohesion

Low cohesion insight detector:

Footnotes

comments powered by Disqus