Cohesion (computer science)

from Wikipedia, the free encyclopedia

In object-oriented programming , cohesion describes how well a program unit maps a logical task or unit. In a system with strong cohesion, each program unit (a method , a class or a module ) is responsible for exactly one well-defined task or unit.

Strong cohesion

The single responsibility principle states that each class only has to fulfill exactly one clearly defined task. This task is fulfilled by the interaction of all attributes and methods of this class. The interaction of the attributes and methods of this class is therefore very close. One speaks of strong cohesion.

Poor ( weak ) cohesion should be avoided. Among other things, it means that common functionalities of a class are not reused, but are implemented several times. Code duplication is therefore a sign of poor cohesion. The DRY principle ( d on't r epeat y ourself , repeat not 'you) helps to avoid this.

Types of cohesion

Cohesion can be seen as a qualitative measure for source code. This measure can be divided into categories, which differ from one another in the strength of cohesion. Possible categories of cohesion from weak cohesion (to be avoided) to strong cohesion (desirable) are:

Random cohesion
Random cohesion occurs when the parts of a module are logically and factually incoherent and are only grouped together at random (example: utility classes).
Logical cohesion
Logical cohesion exists when the - per se different - parts of a module can be logically summarized by a generic term (example: input routines for mouse, keyboard, etc.).
Temporal cohesion
Temporal cohesion exists when the parts of a module are grouped according to their common execution time (example: initialization / destruction within a constructor / destructor).
Procedural Cohesion
Procedural cohesion exists when the parts of a module are grouped according to their execution order (example: a function that first checks access rights and then opens a file).
Communicative cohesion
Communicative cohesion exists when the parts of a module operate on common data.
Sequential Cohesion
Sequential cohesion occurs when the output of one part of a module is the input of another part of the module.
Functional cohesion
Functional cohesion exists when the parts of a module all contribute to the solution of a single, well-defined task.
Informational cohesion
Informational cohesion is a reinforcement of the concept of functional cohesion. It is present if, in addition to functional cohesion, there is also communicative cohesion for a module.

The concept of coupling is closely related to the concept of cohesion .

Footnotes

  1. One usually speaks of code duplication only for certain sequences. Due to the language, there are always irreducible ( token ) sequences in the source text .