Cohesion

A goal of modular programming is to create simple functions that perform a single task, but perform that task well. This can be described as how 'cohesive' a function is.

Two factors that affect the level of cohesion are:

• Number of tasks the function performs.
• Similarity of the tasks.

The following table illustrates the different levels of cohesion:

Number of tasks

Similarity

Cohesion level

Example

1

Not applicable

High

Sin(x)

More than 1

Similar

Moderate

SinAndTan(x)

More than 1

Dissimilar

Low

SinAndLength(x)

Many

Radically different

None

SinAndDateAndTimeAndSQLNext(x)

For example, the function Sin(x) will perform one task - return the trigonometric Sine value of x. This is an example of a highly cohesive function. The function SinAndTan(x) performs two tasks - calculate the trigonometric Sine and Tan of the value X. This function has lower cohesion than Sin(x) because it performs two tasks.

Highly cohesive functions are more dependable, easier to modify, and easier to debug than functions that have lower levels of cohesion and are hence acceptable and encouraged.

Low cohesion functions are typically complex, prone to errors, and are more costly to fix. Low cohesion functions are regarded as poor programming practice and discouraged.