Computer Science › Section H · Software engineering › Topic H.4

Modularity: coupling and cohesion

Nobody can hold a million lines of code in their head, so large systems are split into modules that can be understood, built and changed one at a time. Two ideas measure how well the split was done: coupling between modules should be low, and cohesion within each module should be high.

Why divide software into modules

To change a program safely, you must understand the part you are changing. In a large system that is only possible if the software is divided into manageable units, called modules, each responsible for one part of the overall job. Then a typical change touches only one or two modules, and the rest can be trusted. In imperative programs they are mainly functions, as in "Procedural units: functions and parameters". In object-oriented programs they are objects and the classes that describe them, as in "Object-oriented programming". Larger systems group these into packages, libraries and services.

Two ways to break up a problem

Take a program that prints school report cards. An imperative design starts from the actions: a function make_reports calls read_marks, compute_average, assign_grade and print_card. A structure chart draws this, with each function as a box, an arrow for each call, and labelled arrows for data passed, such as the marks returned by read_marks. It shows which functions depend on which, not how each works. An object-oriented design starts from the things involved instead: Student objects that hold their own marks and report an average, and a ReportCard class that prints one student's results.

Coupling

Coupling is how much modules depend on one another. If A relies on details of B, a change to B may silently break A, so designers aim for low coupling. A classic scale from structured design runs from worst to best. Content coupling: one module reaches into another's internal data or code. Common coupling: modules share global data. Control coupling: one module passes a flag that tells another which of its jobs to do. Stamp coupling: a whole record is passed when only part is needed. Data coupling: only the simple values needed are passed as parameters, which is the loosest useful kind. Some textbooks also call the plain dependency created by a function call control coupling.

The trouble with global data

Global variables, visible to every module, are the commonest source of hidden coupling. Two functions that both read and write a global called total depend on each other, yet nothing in their calls shows it. Someone changing one of them, perhaps to store total in cents instead of dollars, cannot easily find every module affected, and a bug in one module can corrupt data another relies on. Passing data as parameters and return values keeps the same dependency visible in each call.

Worked example: counting hidden coupling

Six functions share three globals. read_input uses scores; validate uses scores and errors; average uses scores and mean; grade uses mean; report uses mean and errors; log_time uses none. 1. Pairs of functions: \(\frac{6 \times 5}{2} = 15\). 2. Pairs sharing at least one global: read_input with validate and with average; validate with average and with report; average with grade and with report; grade with report. That is 7 of the 15 pairs. 3. If mean changes from a decimal to a rounded whole number, three functions must be checked: average, grade and report. 4. Redesign: average returns the mean, and the caller passes it to grade and report as a parameter. The same dependencies now appear in the calls themselves, where a reader can see them.

Cohesion

Cohesion is how well the parts inside one module belong together. A module that does one clear job is easy to name, test and change, so designers aim for high cohesion. The classic scale, weakest first: coincidental, unrelated tasks lumped together, such as a module that prints invoices and resizes photos; logical, similar tasks chosen by a flag, such as one routine for keyboard, file and network input; temporal, tasks grouped only because they happen at the same time; then procedural, communicational and sequential, where steps are linked by order or shared data. Strongest is functional: every part serves a single task, such as computing an average.

Cohesion in classes

For object-oriented designs the same question is asked at two levels. Each method should be functionally cohesive, doing one job that its name describes. The class as a whole should have one clear responsibility, with its methods all working on the same data. A Student class whose methods add a mark, compute an average and report a grade is cohesive; if it also sends emails and formats web pages, it should be split. A useful test is to describe the module in one sentence without using the word "and": if you cannot, it probably does more than one job.

Worked example: removing a control flag

Python code: def format_value(x, mode): with the body if mode == 1: return f"${x:,.2f}" else: return f"{x:.1%}". Callers write format_value(1234.5, 1) to get money and format_value(0.256, 2) to get a percentage. 1. The flag mode is control coupling: every caller must know the function's internal numbering. 2. The function is only logically cohesive, two jobs chosen by a flag. 3. A slip such as format_value(1234.5, 2) prints 123450.0% with no error message. 4. Split it into def format_money(x): return f"${x:,.2f}" and def format_percent(x): return f"{x:.1%}". 5. Check: format_money(1234.5) gives $1,234.50 and format_percent(0.256) gives 25.6%. Each function now has one job, and callers pass only data.

Information hiding

Information hiding means keeping knowledge about a module's internals inside that module: its data, its data structures, its algorithms, any detail other modules do not need. David Parnas argued in a 1972 paper that modules should be chosen around design decisions likely to change, each hidden behind a stable interface. As a design goal, other modules should not need the internals; as an implementation goal, the code enforces the boundary, through local variables and the private members described in "Object-oriented programming". The module becomes a black box whose insides can be rewritten without breaking its users.

Components and reuse

Low coupling, high cohesion and hidden internals make modules reusable. A component is a reusable unit of software with a defined interface, usually one or more classes that work together. Component-based software engineering builds systems mainly by choosing and connecting existing components rather than writing everything new. Python's standard library, Java's class library and the package collections for most languages supply ready-made components for dates, networking, data formats and much more. A well-designed component can be configured or extended without editing its insides. Before relying on one, check its assumptions and its licence.

Common mistakes to avoid

First, mixing up the two terms: coupling is between modules and should be low; cohesion is within a module and should be high. Second, thinking global variables remove coupling because no parameters are passed; they hide it. Third, passing flags that choose what a function does instead of writing separate functions. Fourth, building a utilities module of unrelated helpers, which has coincidental cohesion. Fifth, letting other modules depend on a module's internal data instead of its interface.

Key takeaways

Modularity divides software into units that can be understood and changed separately: functions, classes and objects, packages. Coupling is the dependence between modules; the scale runs from content and common coupling, the worst, through control and stamp coupling to data coupling. Global data creates hidden common coupling. Cohesion is how well a module's parts belong together, from coincidental and logical up to functional. Information hiding keeps internals behind a stable interface. Together these make components reusable.

Flashcards

Flashcard

Module

A unit of software responsible for one part of the overall job

Function, class, package.

Test your understanding

Question 1 of 5

Which design goal is correct for a large system?

Question 2 of 5

A function print_item(item, style) prints a label if style is 1, a receipt if style is 2 and a barcode if style is 3. What does the style parameter create?

Question 3 of 5

Five functions all read and write the same two global variables, and every function uses both. How many pairs of functions are coupled through the globals?

Question 4 of 5

A module called startup opens the log file, resets the score counters and loads the colour settings, only because all three happen when the program begins. What cohesion does it have?

Question 5 of 5

What does information hiding aim to achieve?

← Previous topicNext topic →