0% found this document useful (0 votes)
27 views23 pages

Cohesion by Dr. Choudhary Ravi Singh

Cohesion in software engineering measures how closely related and focused the elements within a module are to achieve a single purpose. High cohesion is essential for maintainability, readability, and reliability of code, with various types of cohesion ranging from functional to coincidental. The document outlines characteristics of high cohesion and provides examples of different types, emphasizing the importance of designing modules with clear, well-defined purposes.

Uploaded by

ravi singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

Cohesion by Dr. Choudhary Ravi Singh

Cohesion in software engineering measures how closely related and focused the elements within a module are to achieve a single purpose. High cohesion is essential for maintainability, readability, and reliability of code, with various types of cohesion ranging from functional to coincidental. The document outlines characteristics of high cohesion and provides examples of different types, emphasizing the importance of designing modules with clear, well-defined purposes.

Uploaded by

ravi singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Cohesion in Software Engineering

𝑫𝒓. 𝑪𝒉𝒐𝒖𝒅𝒉𝒂𝒓𝒚 𝑹𝒂𝒗𝒊 𝑺𝒊𝒏𝒈𝒉


असिस्टें ट प्रोफेिर
कंप्यट
ू र विज्ञान और इंजीननयररंग विभाग
िंगणक विज्ञान एिं असभयांत्रिकी विभाग
Cohesion in Software Design

In software engineering, cohesion refers to the


degree to which the elements within a module
or component of a system are related and work
together to achieve a single, well-defined
purpose. It is a measure of how closely the
responsibilities of a module are aligned and
how focused its functionality is.

High cohesion is needed in software design because it ensures that each module or component within a
system focuses on a single, well-defined purpose, leading to more maintainable, readable, and easily
testable code by minimizing complexity and isolating changes within a specific area, ultimately improving
the overall quality and reliability of the software.

Invertis University, Bareilly


Key Characteristics of High Cohesion

1.Single Responsibility: A highly cohesive module performs one specific


task or a set of closely related tasks.

2.Focused Functionality: All elements within the module contribute to


achieving its primary goal.

3.Ease of Maintenance: Highly cohesive modules are easier to understand,


test, and maintain because they have a clear and limited scope.

4.Reusability: Modules with high cohesion are often more reusable because
they are designed to perform a specific, well-defined function.
Invertis University, Bareilly
Types of Cohesion (from best to worst)

Invertis University, Bareilly


Functional Cohesion
Functional cohesion is the highest and most desirable level of cohesion in
software engineering. It occurs when all elements of a module (such as
functions, methods, or classes) work together to perform a single, well-
defined task.

Invertis University, Bareilly


Functional Cohesion in the Listed Modules:

1.User Management:
1. Purpose: Manages user-related operations such as creating, updating, deleting, and authenticating
users.
2. Functional Cohesion: High, if all functions within this module are directly related to user management
(e.g., user registration, login, profile updates).

2.Product Information Management:


1. Purpose: Handles tasks related to managing product data, such as adding, updating, or retrieving
product details.
2. Functional Cohesion: High, if the module focuses solely on product-related operations (e.g., product
catalog, pricing, descriptions).

3.Order Management:
1. Purpose: Manages the lifecycle of orders, including order creation, tracking, and fulfillment.
2. Functional Cohesion: High, if the module is dedicated to order-related tasks (e.g., placing orders,
updating order status, canceling orders).
Invertis University, Bareilly
4.Inventory Management:
1. Purpose: Tracks and manages inventory levels, stock updates, and product availability.
2. Functional Cohesion: High, if the module focuses exclusively on inventory-related tasks (e.g., stock
updates, low-stock alerts, inventory reports).

5.Payments & Billing:


1. Purpose: Handles payment processing, invoicing, and billing-related tasks.
2. Functional Cohesion: High, if the module is dedicated to payment and billing operations (e.g.,
processing payments, generating invoices, managing subscriptions).

Each module listed appears to have a single, well-defined purpose, which is a key characteristic of
functional cohesion.
If the modules are designed such that all their internal components (e.g., functions, methods, classes)
contribute directly to achieving their respective purposes, then they exhibit high functional cohesion.
For example, in the User Management module, if all functions are related to user operations (e.g., no
unrelated tasks like logging or email notifications are included), it demonstrates functional cohesion.
Invertis University, Bareilly
#include <stdio.h>
int main() {
// Function to calculate the total price of items // Prices of items in the shopping cart
float calculateTotalPrice(float prices[], int itemCount) { float prices[] = {100.0, 200.0, 50.0, 75.0};
float total = 0; int itemCount = sizeof(prices) / sizeof(prices[0]);
for (int i = 0; i < itemCount; i++) {
total += prices[i]; // Discount and tax percentages
} float discountPercent = 10.0; // 10% discount
return total; float taxPercent = 5.0; // 5% tax
}
// Calculate total price
// Function to apply a discount float total = calculateTotalPrice(prices, itemCount);
float applyDiscount(float total, float discountPercent) { printf("Total before discount and tax: $%.2f\n", total);
return total - (total * discountPercent / 100);
} // Apply discount
total = applyDiscount(total, discountPercent);
// Function to add tax printf("Total after discount: $%.2f\n", total);
float addTax(float total, float taxPercent) {
return total + (total * taxPercent / 100); // Add tax
} total = addTax(total, taxPercent);
printf("Final total after tax: $%.2f\n", total);
return 0;
}
calculateTotalPrice: Calculates the total price of all items in the cart. applyDiscount: Applies a discount to the total price.
addTax: Adds tax to the discounted total. main: Calls these functions in sequence to compute the final price.
All functions are focused on the single task of calculating the final price, making this program functionally cohesive.
Invertis University, Bareilly
Sequential Cohesion
Sequential cohesion occurs when the elements of a module are grouped together because
the output of one element is used as the input for the next. In other words, the tasks are
performed in a sequence, where each step depends on the completion of the previous one.

Calculate
Calculate Calculate
Cost of
Radius of Area of
Printing
Circle Circle
the Circle

Invertis University, Bareilly


int main() {
#include <stdio.h> float diameter, costPerUnitArea;
#include <math.h>
// Step 1: Input the diameter of the circle
// Function to calculate the radius of a circle given its diameter printf("Enter the diameter of the circle: ");
float calculateRadius(float diameter) { scanf("%f", &diameter);
return diameter / 2.0;
} // Step 2: Input the cost per unit area for printing
printf("Enter the cost per unit area for printing: ");
// Function to calculate the area of a circle given its radius scanf("%f", &costPerUnitArea);
float calculateArea(float radius) {
return M_PI * radius * radius; // Step 3: Calculate the radius of the circle
} float radius = calculateRadius(diameter);
printf("Radius of the circle: %.2f\n", radius);
// Function to calculate the cost of printing based on the area
float calculatePrintingCost(float area, float costPerUnitArea) { // Step 4: Calculate the area of the circle
return area * costPerUnitArea; float area = calculateArea(radius);
} printf("Area of the circle: %.2f\n", area);

// Step 5: Calculate the printing cost


float printingCost = calculatePrintingCost(area, costPerUnitArea);
Sequential Cohesion: Dependency Between Elements: printf("Cost of printing the circle: %.2f\n", printingCost);
The calculateArea function depends on the output of
calculateRadius. return 0;
The calculatePrintingCost function depends on the output }
of calculateArea. Invertis University, Bareilly
Communication Cohesion
Communicational cohesion occurs when elements of a module are grouped together
because they operate on the same data or input. In other words, the tasks within the module
are related because they all work on the same set of data, even if they perform different
operations.

In a banking system, a module might handle customer account data. The module could include functions to:
•Calculate the account balance.
•Update the customer's personal information.
•Generate a statement for the account.
All these functions operate on the same customer account data, demonstrating communicational cohesion.

Invertis University, Bareilly


#include <stdio.h>
#include <string.h> int main() {
// Create a student object
// Structure to hold student data struct Student A;
struct Student { strcpy(A.name, "John Doe");
char name[50]; A.marks[0] = 85;
int marks[5]; A.marks[1] = 90;
}; A.marks[2] = 78;
A.marks[3] = 88;
// Function to calculate total marks A.marks[4] = 92;
int calculateTotalMarks(struct Student A) {
int total = 0; // Display student details
for (int i = 0; i < 5; i++) { displayStudentDetails(A);
total += A.marks[i];
} return 0;
return total; }
}

// Function to display student details Communicational Cohesion


void displayStudentDetails(struct Student A) { Shared Data: Both functions (calculateTotalMarks and
printf("Student Name: %s\n", A.name); displayStudentDetails) operate on the same Student structure.
printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%d ", A.marks[i]);
}
printf("\nTotal Marks: %d\n", calculateTotalMarks(A));
Invertis University, Bareilly
}
Procedural Cohesion
Procedural cohesion occurs when elements of a module are grouped together because they are executed in a
specific sequence. The tasks within the module are related by the order in which they are performed, rather than
by the data they operate on or the specific function they perform.

Consider a program that processes a customer order.


The module might include functions to:
1.Validate the order.
2.Calculate the total cost.
3.Generate an invoice.
4.Update the inventory.

These tasks are grouped together because they must be performed in a specific sequence to
process an order, demonstrating procedural cohesion.

Invertis University, Bareilly


Here’s a simple C program that demonstrates procedural cohesion. The program
processes a student's exam marks and performs the following tasks in sequence:
1.Input the student's marks.
2.Calculate the total marks.
3.Calculate the average marks.
4.Display the results.

•The tasks are grouped together because they must be performed in a specific sequence.
•The focus is on the sequence of tasks rather than a single, well-defined purpose.

Invertis University, Bareilly


#include <stdio.h> // Function to display results
void displayResults(int total, float average) {
// Function to input student marks printf("Total Marks: %d\n", total);
void inputMarks(int marks[], int size) { printf("Average Marks: %.2f\n", average);
printf("Enter marks for %d subjects:\n", size); }
for (int i = 0; i < size; i++) { int main() {
printf("Subject %d: ", i + 1); const int numSubjects = 5;
scanf("%d", &marks[i]); int marks[numSubjects];
} int total;
} float average;
// Function to calculate total marks // Step 1: Input marks
int calculateTotalMarks(int marks[], int size) { inputMarks(marks, numSubjects);
int total = 0;
for (int i = 0; i < size; i++) { // Step 2: Calculate total marks
total += marks[i]; total = calculateTotalMarks(marks, numSubjects);
}
return total; // Step 3: Calculate average marks
} average = calculateAverageMarks(total, numSubjects);
// Function to calculate average marks
float calculateAverageMarks(int total, int size) { // Step 4: Display results
return (float)total / size; displayResults(total, average);
}
return 0;
Invertis University, Bareilly }
Temporal Cohesion

Temporal cohesion in software design refers to grouping tasks or functions that are related by time. This
means that elements are bundled together because they need to happen at the same time .
For example, initializing all system settings at “startup” or closing all files at “shutdown” are tasks with
temporal cohesion.

Another example is a “session timeout” function in a web application. This function might include tasks like
logging out the user, saving session data, and clearing cookies. These tasks are grouped together because they all
need to happen when the user's session expires, even though they involve different operations like
authentication, data storage, and browser management.

In an e-commerce application, a "checkout" process is an example of temporal cohesion. It includes tasks like
calculating the total price, applying discounts, validating payment details, and confirming the order. These tasks
are grouped together because they all need to happen during the checkout phase, even though they involve
different functionalities like pricing logic, payment processing, and order management.
Invertis University, Bareilly
#include <stdio.h> // Main function grouping tasks with temporal cohesion

// Functions representing tasks that happen during startup int main() {


void initializeSystem() { // Tasks grouped because they happen at the same time (startup)
printf("Initializing system...\n"); initializeSystem();
} loadConfiguration();
connectToDatabase();
void loadConfiguration() { printf("Startup complete!\n");
printf("Loading configuration...\n"); return 0;
} }

void connectToDatabase() {
printf("Connecting to database...\n");
}

The tasks (initializeSystem, loadConfiguration, connectToDatabase) are grouped together in main


because they all need to happen during the program's startup phase.

They are temporally cohesive because they are related by timing (all occur at the start), even though
they perform different functions. Invertis University, Bareilly
Logical Cohesion
Elements in a logically cohesive module perform similar tasks. The elements are related by a general theme
or category, but not by functionality.

It can make the code harder to maintain or understand, as the grouped elements may not have a clear
relationship.
Imagine a module in a program that handles
different types of file operations, such as:

1.Reading a file
2.Writing to a file
3.Deleting a file
4.Compressing a file

These tasks are logically related because they all


deal with files, but they serve very different
purposes and don’t necessarily depend on each
other. Grouping them together is an example of
logical cohesion. Invertis University, Bareilly
#include <stdio.h>
int main() {
// A function that performs different math operations based on a int a = 10, b = 5;
parameter
void mathOperation(int operation, int a, int b) { // Perform different math operations
switch (operation) { mathOperation(1, a, b); // Addition
case 1: mathOperation(2, a, b); // Subtraction
printf("Addition: %d + %d = %d\n", a, b, a + b); mathOperation(3, a, b); // Multiplication
break; mathOperation(4, a, b); // Division
case 2:
printf("Subtraction: %d - %d = %d\n", a, b, a - b); return 0;
break; }
case 3: The mathOperation function groups tasks that are
printf("Multiplication: %d * %d = %d\n", a, b, a * b); logically related (all involve math operations) but
break; serve different purposes (addition, subtraction,
case 4: multiplication, division).
printf("Division: %d / %d = %d\n", a, b, a / b);
break; This is an example of logical cohesion because the
default: tasks are grouped under a general theme (math
printf("Invalid operation!\n"); operations) rather than being functionally
} connected.
} Invertis University, Bareilly
Coincidental Cohesion
Coincidental cohesion is the weakest type of cohesion in software design. It occurs when elements (like
functions or code blocks) are grouped together arbitrarily, with no meaningful relationship between them.
The grouping is purely coincidental, often for convenience or because there was no better place to put
them.
•The elements have no logical, functional, or meaningful connection.
•The grouping makes the code harder to understand, maintain, and reuse.

Imagine a module in a project that contains completely unrelated functions, like:

1.A function to calculate the area of a circle.


2.A function to send an email.
3.A function to sort a list of numbers.
4.A function to generate a random password.

These functions are grouped together arbitrarily, with no logical or functional


connection. This is coincidental cohesion.
Invertis University, Bareilly
#include <stdio.h>
int main() {
// A function to calculate the area of a circle // Calling unrelated functions grouped together arbitrarily
void calculateCircleArea(float radius) { calculateCircleArea(5.0);
float area = 3.14 * radius * radius; sendEmail("[email protected]");
printf("Area of circle: %.2f\n", area); int arr[] = {3, 1, 2};
} sortNumbers(arr, 3);
generatePassword();
// A function to send an email (dummy implementation)
void sendEmail(char* recipient) { return 0;
printf("Email sent to: %s\n", recipient); }
}

// A function to sort a list of numbers (dummy implementation) The functions calculateCircleArea, sendEmail,
void sortNumbers(int arr[], int size) { sortNumbers, and generatePassword have no
printf("Numbers sorted (dummy output).\n"); meaningful relationship.
}
They are grouped together purely by
// A function to generate a random password (dummy implementation) coincidence, making the code harder to
void generatePassword() { understand and maintain.
printf("Generated password: XYZ123\n");
} This is an example of coincidental cohesion.
Invertis University, Bareilly
Relationship with Coupling

Cohesion is often discussed alongside coupling, which refers to the degree of interdependence between modules.
Ideally, software should have high cohesion and low coupling, meaning modules are self-contained and interact
with each other in a minimal and well-defined way. This combination leads to more maintainable, scalable, and
robust software systems.

Invertis University, Bareilly

You might also like