Cohesion and coupling
What you will learn on this page
Section titled “What you will learn on this page”- What cohesion and coupling mean, in plain words, and why they are usually discussed together.
- The common kinds of coupling, from the loosest to the tightest, with a C++ example of each and how to loosen it.
- How to measure cohesion by hand with a data-usage table, and two quick tests: the one-sentence test and the “who asks for changes” test.
- How to reduce coupling without breaking a design into dozens of tiny classes that are coupled to each other instead.
- When some coupling is the right choice.
The problem
Section titled “The problem”A bicycle repair shop sends invoices to its customers, some of them in other countries. The owner describes what the program must do:
| ID | Requirement |
|---|---|
| FR-1 | Each invoice gets the next number: 1, 2, 3, and so on. |
| FR-2 | An invoice lists lines: a description, a quantity, and a unit price. |
| FR-3 | VAT is added at the rate of the customer’s country on the day the invoice is created. |
| FR-4 | An invoice can be printed as text, at any time, for example again at the end of the year for the accountant. |
| FR-5 | When a country changes its VAT rate, new invoices use the new rate. |
The first version works for months. Then the accountant finds that an invoice printed again in December shows a different total from the one the customer paid in June. Nobody changed the invoice. The VAT rate for the customer’s country changed, and the program recomputed the tax with today’s rate. FR-3 and FR-4 together say that must not happen.
(The countries are real, but the rates on this page are made up for the example.) The cause is not a typo. It is how the parts of the program are connected, and that is what this page is about.
Two ideas
Section titled “Two ideas”| Idea | In plain words | Good when |
|---|---|---|
| Cohesion | How strongly the things inside one class (or file, or module) belong together. | High: every member serves one purpose; a change to that purpose stays inside. |
| Coupling | How much one part must know about another to work. | Low: each part knows only what it must, through a small interface. |
They are two views of the same question: where should the lines between parts go? Draw a line through the middle of a cohesive group, and the two halves must talk to each other a lot (high coupling). Put unrelated things in one class, and every change to one of them disturbs the others (low cohesion). Good boundaries give high cohesion and low coupling at the same time.
Coupling is never zero. A program whose parts know nothing about each other does nothing. The aim is coupling that is small, visible, and stable: few names, all in the header, unlikely to change.
Kinds of coupling
Section titled “Kinds of coupling”Some kinds of coupling are much looser than others. This ladder runs from the loosest to the tightest. The names are traditional; what matters is being able to recognise each one.
| Kind | What one part knows about another | C++ example | How to loosen it |
|---|---|---|---|
| data | only the values it is given | tax_on(int cents, int percent) |
usually the goal |
| stamp | a whole structure, when it uses one field | int percent_for(const Customer& c) that reads only c.country |
pass the field: percent_for(const std::string& country) |
| control | a flag that chooses what the other part does | render(number, bool html), total_cents(number, bool with_tax) |
two functions (render_text, render_html) |
| common | shared global data that both read or write | inline std::map<std::string, int> vat_percent read by several functions |
give the data an owner and pass it, or ask the owner (TaxRates) |
| content | the other part’s internals: its private data or how it works inside | a friend added only so another class can change private members directly; code that depends on another class’s memory layout |
use the public interface; if it is missing something, add it there |
Two more kinds do not fit the ladder but are just as common:
- Coupling to a concrete type.
class ReportWriter { SqlDatabase db_; }cannot be tested without a database. An interface or a smaller type loosens it (PRN-04 and the dependency-injection lessons). - Temporal coupling (coupling to an order of calls). “Call
load()beforetotal()” is a rule the compiler cannot check. A constructor that does the loading, or a type that only exists once loaded, removes it.
The bigger the step down the ladder, the more a change in one part breaks the other, and the less you can tell from a function’s signature what it depends on. A function that reads a global has a dependency that no caller can see.
Measuring cohesion: the data-usage table
Section titled “Measuring cohesion: the data-usage table”Cohesion sounds vague, but it can be checked by hand. List the member functions as rows and the data members (and any globals) as columns. Mark which data each function reads or writes. Here is the first version of the invoicing code:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Before: one service does numbering, storage, tax, and two output formats.// This is the flawed design. Read it for where the tax rate comes from:// a global table that any code can change, read again every time an// invoice is totalled or printed.namespace before {
// Every invoice reads this table whenever it computes tax.// The table maps a country code to a VAT percent: "IE" -> 23, and so on.// `inline` lets a header define a variable that every file sees as one// shared object. It is not const, so any code anywhere can write// before::vat_percent["IE"] = 21, and no function signature warns that// totals and printouts depend on it. That is the bug this page is about.inline std::map<std::string, int> vat_percent{{"DE", 19}, {"FR", 20}, {"IE", 23}};
// Numbers, stores, totals, and prints invoices, all in one class. An// invoice is known to callers only by its number: they create one, then// pass the number back to every other call. Each call that takes a number// uses invoices_.at(number), which throws std::out_of_range for a number// that was never created.class InvoiceService {public: // Starts a new, empty invoice for this customer and returns its number // (1, 2, 3, ...). int create(const Customer& customer); // Adds one line to invoice `number`. The Line is taken by value and // then moved into the invoice's list. void add_line(int number, Line line); // with_tax false: the subtotal; true: subtotal plus tax. // The bool is a switch the caller flips to pick a path inside the // function (control coupling). The tax uses today's rate from the // global table, not the rate when the invoice was issued. With // with_tax true, throws std::out_of_range if the customer's country is // not in the table. [[nodiscard]] int total_cents(int number, bool with_tax) const; // html false: plain text; true: an HTML table. // Another switch: one function holding two unrelated layouts. [[nodiscard]] std::string render(int number, bool html) const;
private: // What is kept for one invoice: who it is for, and its lines. Note what // is missing: the tax rate. It is looked up again each time instead. struct Draft { Customer customer; std::vector<Line> lines; }; // Every invoice, found by its number. All four functions use this map, // which is why the class looks cohesive at first sight. std::map<int, Draft> invoices_; // The number the next create() hands out. Only create() uses it. int next_number_ = 1;};
} // namespace before| Member function | invoices_ |
next_number_ |
global vat_percent |
Purpose |
|---|---|---|---|---|
create |
✔ | ✔ | numbering and storage | |
add_line |
✔ | storage | ||
total_cents |
✔ | ✔ | tax calculation | |
render |
✔ | ✔ | formatting (two ways) |
Read the table, not the class name:
next_number_is used by one function only. Numbering is a separate job that happens to live here.- The global is a column. Two functions depend on data that the class
does not own and cannot protect. That is common coupling, and it is the
cause of the bug:
renderreads today’s rate. - Every function uses
invoices_, which looks cohesive. But the “purpose” column has four different answers. One map is shared by four jobs.
Two quick tests give the same answer:
- The one-sentence test. Describe the class in one sentence without
“and”. “
InvoiceServicenumbers invoices and stores them and computes tax and prints them in two formats.” Each “and” is a candidate split. - The “who asks for changes” test. List who would ask for a change to each part. The tax rules change when a government changes them. The layout changes when the owner wants a logo. The numbering changes when the accountant wants a yearly prefix. Three different people, three reasons to change one class. (The single-responsibility principle, PRN-08, builds on this test.)
Kinds of cohesion
Section titled “Kinds of cohesion”Cohesion also has traditional names, from the weakest to the strongest. They are useful for spotting a weak group; there is no need to memorise them.
| Kind | Why the things are together | Example |
|---|---|---|
| coincidental | no reason; they had to go somewhere | Utils with trim, send_email, and vat_for |
| logical | they are the same kind of thing | Validators holding every validation function in the program |
| temporal | they run at the same time | startup() that opens the log, loads the rates, and connects to the printer |
| procedural | they run in a fixed order, but pass no data to each other | open_shop() that unlocks the till, switches on the lights, then prints the day sheet |
| communicational | they work on the same data | InvoiceService above: everything touches invoices_ |
| sequential | the output of one is the input of the next | parse a line, then validate it, then convert it |
| functional | together they do one well-defined job, and nothing else | TaxRates: set a rate, look up a rate |
InvoiceService is communicational: better than a grab bag, but it still
mixes four jobs. The aim is functional cohesion for each class.
Bad, good, great: where does the tax rate live?
Section titled “Bad, good, great: where does the tax rate live?”The key move was not “split the class”. It was to ask which part needs
to know the rate, and when. Only Invoicing::create needs today’s rate.
Everything after creation needs the invoice’s rate, which is a fact about
the invoice.
The new design
Section titled “The new design”class TaxRates
the current rate per country
Data members
std::map<std::string, int> percent_by_country_;
Member functions
void set(const std::string& country, int percent);throws outside 0 to 100int percent_for(const std::string& country) const;throws if unknown
class Invoicing
creates invoices: numbering and today's rate
Data members
const TaxRates& rates_;not owned; must outlive thisint next_number_ = 1;
Member functions
explicit Invoicing(const TaxRates& rates);explicit Invoicing(TaxRates&&) = delete;a temporary would leave rates_ danglingInvoice create(const Customer& customer);throws if no rate
class Invoice
one invoice; its rate never changes
Data members
int number_;std::string bill_to_;int tax_percent_;fixed when createdstd::vector<Line> lines_;
Member functions
Invoice(int number, std::string bill_to, int tax_percent);throws on bad valuesvoid add_line(Line line);throws on bad valuesint number() const;const std::string& bill_to() const;int tax_percent() const;std::span<const Line> lines() const;valid until the next add_line or the invoice is destroyedint subtotal_cents() const;int tax_cents() const;int total_cents() const;
struct Line
value: a plain record
Data members
std::string description;int quantity = 0;int unit_cents = 0;
render_text(const Invoice&) is a free function, not a member, so it is
not in the outline. Printing is a separate job that uses an invoice’s
public functions; making it a member would put a layout decision inside
Invoice.
Run the data-usage table again on Invoice: the three calculating
functions use lines_ and tax_percent_, and the other functions return
one fact about the same invoice. Every member is about one invoice, and the
one-sentence test passes (“an
invoice holds its lines and computes its totals at its own rate”). Notice
also what Invoice no longer stores: the customer’s email and country.
It needs only the name to print (bill_to_), so Invoice no longer
knows Customer at all. Invoicing::create still takes a whole
Customer and uses two of its fields. That is mild stamp coupling, and it
is acceptable here: Customer is a small, stable record.
The dependencies, before and after:
Text description of the diagram
Two parts. Before: the InvoiceService box (numbering, storage, tax, two formats) has a dashed arrow labelled “reads at print time” to a global vat_percent table, and a solid arrow labelled “owns 0..*” to Draft, which holds a whole Customer and the lines. After: Invoicing (numbering) has a dashed arrow labelled “reads once, at create” to TaxRates, and a dashed arrow labelled “creates” to Invoice, which holds its own rate and its lines. render_text has a dashed “uses” arrow to Invoice. Nothing in After points to Invoicing or to render_text, and Invoice points to nothing. (Plain records such as Line and Customer, and small helpers, are not drawn.)
Diagram source (Mermaid)
flowchart LR
subgraph Before
S["InvoiceService<br/>numbering, storage,<br/>tax, two formats"] -.->|reads at print time| G[("global<br/>vat_percent")]
S -->|"owns 0..*"| D["Draft<br/>a whole Customer, lines"]
end
subgraph After
I["Invoicing<br/>numbering"] -.->|reads once, at create| R["TaxRates"]
I -.->|creates| V["Invoice<br/>its own rate, lines"]
F["render_text"] -.->|uses| V
endInvoicing::create is the only place that reads the rates:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The only place that reads today's rate. It looks the rate up first and// only then takes a number, so the order of the two lines matters.Invoice Invoicing::create(const Customer& customer) { const int percent = rates_.percent_for(customer.country); // may throw: nothing changed yet // next_number_++ hands out the current value and then adds one to it: // the first invoice gets 1 and next_number_ becomes 2. The rate goes // into the Invoice as a plain int, so later rate changes cannot reach it. return Invoice{next_number_++, customer.name, percent};}The number is taken only after the lookup succeeds, so an unknown country does not use up a number: no number is lost to a failed lookup. (Keeping numbers gap-free across program runs, or when a caller throws an invoice away, would need the numbers to be stored; the example does not do that.)
Check: change the rate after issuing an invoice
Section titled “Check: change the rate after issuing an invoice”The example program issues the same invoice with both designs, then changes Ireland’s rate from 23% to 21% and prints invoice 1 again:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One customer in Ireland and two lines: 2 x 12.50 and 1 x 40.00, so a// subtotal of 6500 cents. The braces fill the struct fields in order.const Customer ana{"Ana Byrne", "ana@example.com", "IE"};const Line pads{"Brake pads", 2, 1250};const Line labour{"Labour (1 hour)", 1, 4000};
// The old design: the service keeps the invoice, and we keep its number.before::InvoiceService service;const int number = service.create(ana);service.add_line(number, pads);service.add_line(number, labour);
// The new design: a rate table, a creator that reads it, and an Invoice// object that we hold ourselves. `rates` is declared first so that it// outlives `invoicing`, which keeps a reference to it. create() looks// up Ireland's 23% now and stores it in `first`.TaxRates rates;rates.set("DE", 19);rates.set("FR", 20);rates.set("IE", 23);Invoicing invoicing{rates};Invoice first = invoicing.create(ana);first.add_line(pads);first.add_line(labour);
std::cout << "-- before: issued --\n" << service.render(number, false);std::cout << "-- after: issued --\n" << render_text(first);
// Months later, the rate changes. Invoice 1 is printed again for the records.// The old design reads the global again and prints 21%; the new invoice// still holds 23%, because changing `rates` affects only invoices// created after this point.before::vat_percent["IE"] = 21;rates.set("IE", 21);
std::cout << "-- before: printed again --\n" << service.render(number, false);std::cout << "-- after: printed again --\n" << render_text(first);-- before: issued --Invoice 1 for Ana Byrne 2 x Brake pads @ 12.50 = 25.00 1 x Labour (1 hour) @ 40.00 = 40.00Subtotal: 65.00VAT 23%: 14.95Total: 79.95-- after: issued --Invoice 1 for Ana Byrne 2 x Brake pads @ 12.50 = 25.00 1 x Labour (1 hour) @ 40.00 = 40.00Subtotal: 65.00VAT 23%: 14.95Total: 79.95-- before: printed again --Invoice 1 for Ana Byrne 2 x Brake pads @ 12.50 = 25.00 1 x Labour (1 hour) @ 40.00 = 40.00Subtotal: 65.00VAT 21%: 13.65Total: 78.65-- after: printed again --Invoice 1 for Ana Byrne 2 x Brake pads @ 12.50 = 25.00 1 x Labour (1 hour) @ 40.00 = 40.00Subtotal: 65.00VAT 23%: 14.95Total: 79.95The two designs agree when the invoice is issued: a subtotal of 65.00, VAT of 14.95 at 23%, and a total of 79.95. After the rate changes, the old design prints 21% and a total of 78.65 for an invoice the customer has already paid at 79.95. The new design prints the invoice as it was issued.
Both tax amounts in the output happen to be whole cents. The tests check the totals and one case that needs rounding (19% of 19.99), that an issued invoice keeps its rate while a new one gets the new rate, that a failed create uses no number, that bad values are refused, and that both designs print exactly the same text when no rate has changed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp. standard_rates(), defined above// this snippet, returns a TaxRates with DE at 19% and IE at 23%.
// Builds invoices directly (no TaxRates needed) and checks the sums.// 2 x 1250 + 4000 = 6500 cents; 23% of 6500 is exactly 1495. The second// invoice needs rounding: 19% of 1999 is 379.81 cents, which rounds to 380.LLD_TEST(totals_add_the_lines_and_round_the_tax) { Invoice invoice{1, "Ana Byrne", 23}; invoice.add_line({"Brake pads", 2, 1250}); invoice.add_line({"Labour (1 hour)", 1, 4000}); LLD_CHECK(invoice.subtotal_cents() == 6500); LLD_CHECK(invoice.tax_cents() == 1495); LLD_CHECK(invoice.total_cents() == 7995);
Invoice chain{2, "Ben Okafor", 19}; chain.add_line({"Chain", 1, 1999}); LLD_CHECK(chain.tax_cents() == 380); // 379.81 cents, rounded to the nearest cent}
// The bug from the old design, tested on the new one: an invoice made// before a rate change keeps 23%, and only the one made after gets 21%.// `rates` is not const here because the test changes it.LLD_TEST(an_issued_invoice_keeps_its_rate) { TaxRates rates = standard_rates(); Invoicing invoicing{rates}; const Invoice first = invoicing.create({"Ana Byrne", "ana@example.com", "IE"}); rates.set("IE", 21); const Invoice second = invoicing.create({"Ana Byrne", "ana@example.com", "IE"}); LLD_CHECK(first.tax_percent() == 23); LLD_CHECK(second.tax_percent() == 21);}
// "XX" has no rate, so the second create throws std::out_of_range. The// next successful create still gets number 2, which proves that the failed// call did not use up a number. (void) says the result is ignored on// purpose; create is [[nodiscard]].LLD_TEST(numbers_follow_on_and_a_failed_create_uses_none) { const TaxRates rates = standard_rates(); Invoicing invoicing{rates}; LLD_CHECK(invoicing.create({"A", "a@example.com", "DE"}).number() == 1); LLD_CHECK_THROWS((void)invoicing.create({"B", "b@example.com", "XX"}), std::out_of_range); LLD_CHECK(invoicing.create({"C", "c@example.com", "DE"}).number() == 2);}
// A rate of 101% and a line with quantity 0 are both refused, and the// refused line was not stored: lines() is still empty.LLD_TEST(bad_values_are_rejected) { TaxRates rates; LLD_CHECK_THROWS(rates.set("IE", 101), std::invalid_argument); Invoice invoice{1, "Ana Byrne", 23}; LLD_CHECK_THROWS(invoice.add_line({"Nothing", 0, 100}), std::invalid_argument); LLD_CHECK(invoice.lines().empty());}
// The same invoice made with both designs (Germany, one line, no rate// change) must print exactly the same text. This shows the new design// kept the old output while moving the rate into the invoice.LLD_TEST(both_designs_print_the_same_text_until_a_rate_changes) { const Customer ana{"Ana Byrne", "ana@example.com", "DE"}; before::InvoiceService service; const int number = service.create(ana); service.add_line(number, {"Chain", 1, 1999});
const TaxRates rates = standard_rates(); Invoicing invoicing{rates}; Invoice invoice = invoicing.create(ana); invoice.add_line({"Chain", 1, 1999});
LLD_CHECK(service.render(number, false) == render_text(invoice));}The example keeps some simplifications that a real billing system would
not. Money is an int count of cents, which can overflow for very large
invoices; a real system would use a wider or dedicated money type.
euros assumes the amount is not negative, so credit notes would need more
work. And the span returned by lines() is a view: it stays valid only
until the next add_line or until the invoice is destroyed.
Reducing coupling without fragmenting
Section titled “Reducing coupling without fragmenting”Splitting a class lowers coupling only if the parts can do their jobs without talking to each other all the time. Split too finely, and the coupling moves between the pieces:
class LineTotalCalculator
quantity times price
Member functions
int total(const Line& line) const;
class SubtotalCalculator
uses LineTotalCalculator
Member functions
int subtotal(std::span<const Line> lines) const;
class TaxRateFinder
uses TaxRates
Member functions
int percent(const std::string& country) const;
class TaxAmountCalculator
uses SubtotalCalculator and TaxRateFinder
Member functions
int tax(std::span<const Line> lines, const std::string& country) const;
class InvoiceTotalCalculator
uses SubtotalCalculator and TaxAmountCalculator
Member functions
int total(std::span<const Line> lines, const std::string& country) const;
Five classes, none owning data (one holds a reference to TaxRates), and
most need one or two of the others. To understand how a total is computed, a reader opens five files.
The country is passed through three layers. The tax is still computed from
today’s rate, so the bug is still there. (An outline for discussion; not
compiled.)
Guidelines for where to split:
- Split where the data-usage table splits. If two groups of functions use different data, they are two classes. If they use the same data, keep them together.
- Split where the reasons to change differ. Tax rules, layout, and
numbering change for different people. Subtotal and total change
together, so they stay together in
Invoice. - Keep a rule with the data it reads (finding classes, step 7).
subtotal_centsreadslines_, so it belongs toInvoice, not to a calculator. - Count the arrows (a rule of thumb, not a law). After a split, draw the dependencies. If there are more arrows between the new parts than there are jobs, the split has probably gone too far.
Measuring coupling informally
Section titled “Measuring coupling informally”There is no single number, but these questions work in a code review:
| Question | Before | After |
|---|---|---|
| What must a test set up to check the tax on one invoice? | a service, a customer, the global | an Invoice with a rate |
| Which parts change if the rule for which rate applies changes? | total_cents and render |
Invoicing::create |
| Which parts change if the layout changes? | render, next to the tax code |
render_text only |
| Can you tell from the signatures what each function depends on? | no: the global is hidden | yes |
| How many names from other parts does each part use? | InvoiceService: the global, Customer, Line |
Invoice: Line; render_text: Invoice, Line; Invoicing: Customer, TaxRates, Invoice |
When not to
Section titled “When not to”Low coupling and high cohesion are not goals on their own; they are ways to make change cheap. They are worth less when:
- The code is small and will not change. A 40-line tool that prints one report does not need four classes.
- Two parts always change together. If every change to A also changes B, coupling them tightly (one class, or one file) is honest. Splitting them only adds an interface to maintain.
- Performance needs the data close together. Code that processes millions of items may keep data in one array and loop over it in one function on purpose. Measure first, and keep the decision in one place.
A global is also sometimes right: a logger, or a constant table that never
changes (constexpr). The danger is global data that changes, as
vat_percent did.
Trade-offs
Section titled “Trade-offs”| Benefit | Cost |
|---|---|
| A change stays inside one part | More types and files to name and find |
| Each part can be tested with little setup | Dependencies must be passed in (constructor parameters, references with lifetimes) |
| Signatures show what each part depends on | Longer constructor parameter lists |
Parts can be reused (render_text for any invoice) |
A wrong split is costly, because the pieces now depend on each other |
Common mistakes
Section titled “Common mistakes”- Mutable global data, read by functions whose signatures do not show it.
boolparameters that choose a path, so one function holds two unrelated behaviours.- Passing a whole object when one field is needed, so the callee depends on everything in it.
- Splitting by step (calculator, finder, writer) instead of by data and reasons to change, which multiplies the arrows.
- Naming a class after a technical role (
Manager,Service,Utils): the name gives no hint of what belongs in it, so everything does. - Measuring cohesion by the class name instead of by what the functions use.
When a requirement changes
Section titled “When a requirement changes”The shop starts doing repairs for a charity, which has a tax-exemption certificate. An exempt customer pays 0% VAT.
In the old design, two functions read the global rate, total_cents
and render. Both must learn about exemptions, in the same way. If only
one is changed, the printed VAT and the total disagree.
In the new design, only the place that chooses the rate changes. The
customer record gains a field, and Invoicing::create gains one condition.
Invoice, TaxRates, and render_text do not change, and every existing
test still passes, because an invoice already just stores the rate it was
given. The changed function, as a sketch (it was syntax-checked, but it is
not part of the compiled example):
struct Customer { std::string name; std::string email; std::string country; bool tax_exempt = false; // new: false unless a certificate is on file};
// The one function that changes. `?:` reads "if the condition is true, the// first value, otherwise the second": an exempt customer gets 0 without// looking up the rates at all, so an exempt customer in a country with no// rate does not throw. Everyone else gets today's rate, as before.Invoice Invoicing::create(const Customer& customer) { const int percent = customer.tax_exempt ? 0 : rates_.percent_for(customer.country); return Invoice{next_number_++, customer.name, percent};}A new test would create an invoice for an exempt customer in a country with
a rate and check that tax_percent() is 0.
Exercise: Rank four classes by cohesion
For each class, say which kind of cohesion it has (use the table above), rank the four from weakest to strongest, and say how you would improve the weakest two.
// `static` member functions are called on the class, as// StringHelpers::trim(text), without making an object first.class StringHelpers {public: static std::string trim(std::string_view text); static std::string format_money(int cents); static bool send_email(const std::string& to, const std::string& body); static int vat_for(const std::string& country);};
class Startup {public: void run(); // opens the log file, loads the tax rates, connects to the printer};
class Order {public: void add_line(Line line); bool cancel(); [[nodiscard]] int total_cents() const; // const: reads the order, changes nothingprivate: std::vector<Line> lines_; bool cancelled_ = false;};
class MonthEnd {public: // Reads the month's invoices, totals them by country, and writes a CSV file. void run(const std::string& month, const std::string& csv_path);};Then name the kind of coupling in each of these calls:
print_receipt(order, true), wheretruemeans “include prices”.days_overdue(invoice), which reads onlyinvoice.due_day().next_number(), which increments a global counter.
Show the explained answer
Ranking, weakest first.
| Class | Kind | Why |
|---|---|---|
StringHelpers |
coincidental | Sending email and looking up VAT have nothing to do with strings or with each other. |
Startup |
temporal | The three jobs are together only because they happen at the same moment. |
MonthEnd |
sequential | Each step feeds the next, but reading, totalling, and writing a file are three concerns. |
Order |
functional | Every function uses lines_ or cancelled_ and serves one job: an order and its rules. |
Improving the weakest two. Move each function in StringHelpers to
the part that owns its job: trim to a small text utility (that one is
fine as a free function), format_money next to the money type,
send_email behind an email interface, and vat_for into TaxRates.
For Startup, keep run() if you like (some code has to start things),
but let it only call the owners: the log opens itself in its constructor,
TaxRates loads itself, the printer connection is a class. Then run()
is a short list of calls with no logic of its own.
MonthEnd would come next: split totalling (a pure function from a
sequence of invoices to totals by country, easy to test) from reading and
writing, which the next lesson, on separation of concerns, covers.
Coupling in the calls.
- Control coupling. The
boolchooses a path insideprint_receipt. Better: two functions. Anenum classstill chooses a path inside, but at least makes the call readable. - Stamp coupling. The function needs one day but takes the whole
invoice. Better:
days_overdue(Day due, Day today), which also makes the hidden “today” visible. - Common coupling. A hidden global, changed by every call. Better: an
object that owns the counter (like
Invoicing), passed to whoever needs numbers.
Summary
Section titled “Summary”- Cohesion is how strongly the things inside a part belong together; coupling is how much one part must know about another. Good boundaries give high cohesion and low coupling.
- Coupling runs from data (only the values needed) through stamp, control, and common (shared globals) to content (another part’s internals). Move down the ladder towards data coupling.
- Measure cohesion with a data-usage table, the one-sentence test, and the “who asks for changes” test.
- Ask which part needs to know a fact, and when. In the invoice, only creation needs today’s rate; the invoice keeps its own.
- Split where data usage and reasons to change split. Splitting by step moves coupling between the pieces instead of removing it.
- Tight coupling is honest when two parts always change together.