Here is an example of coupling and cohesion in Python:
Imagine that we have a program that processes and analyzes data from a CSV file.
We could implement this program using three modules:
1. reader.py: This module reads the data from the CSV file and
returns it as a list of dictionaries.
2. processor.py: This module takes the list of dictionaries returned by the reader
and performs some analysis on the data, returning the results as another list of dictionaries.
3. writer.py: This module takes the list of dictionaries returned by the processor and writes it to a new CSV file.
In this example, the reader module is highly coupled to the processor module because the processor
module relies heavily on the data returned by the reader. The processor module is also highly coupled
to the writer module because it depends on the writer module to save its results.
On the other hand, the reader module has low coupling to the writer module because it does not depend
on the writer module to function.
In terms of cohesion, the reader module has high cohesion because all the elements within it work
together towards the single goal of reading data from a CSV file. Similarly, the processor module
has high cohesion because all the elements within it work together towards the single goal of analyzing the data.
The writer module also has high cohesion because all the elements within it work together towards the single goal
of writing the data to a CSV file.
Overall, this design exhibits low coupling and high cohesion, which are generally desirable
characteristics in software design.
import csv
def read_data(file_path):
data = []
with open(file_path, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
data.append(row)
return data
def process_data(data):
results = []
for row in data:
result = {
'name': row['name'],
'age': row['age'],
'income': row['income']
}
results.append(result)
return results
import csv
def write_data(data, file_path):
with open(file_path, 'w') as f:
fieldnames = ['name', 'age', 'income']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
import reader
import processor
import writer
data = reader.read_data('input.csv')
results = processor.process_data(data)
writer.write_data(results, 'output.csv')