Low Coupling & High Cohesion
Low Coupling & High Cohesion (GRASP)
"High cohesion: keep elements with strongly related responsibilities together. Low coupling: minimise dependencies between classes." — Craig Larman
"High cohesion and low coupling are not separate goals — they emerge together when the boundaries are drawn correctly." — OOP community wisdom
Core idea
Cohesion is how strongly the methods and data of one class are tied to a shared theme. Coupling is how much a class knows about and depends on other classes. Good design = high cohesion inside + low coupling outside.
High Cohesion — internal integrity
What it is
All the methods and fields of the class work toward one goal. If you can describe the class in one sentence without "and", cohesion is high.
| Cohesion | Class description | Example |
|---|---|---|
| High ✅ | "This is Order. It manages its items and discounts." | Order with add_item, total, apply_discount |
| Low ❌ | "This is CustomerManager. It handles profile, orders, notifications, billing, and analytics." | God class |
Seven levels of cohesion (Stevens, Myers & Constantine, 1974)
From best to worst:
- Functional — all methods perform one function. The best.
- Sequential — the output of one method is the input of the next.
- Communicational — methods operate on the same data.
- Procedural — methods are called in a certain order (lifecycle, for example).
- Temporal — methods are called at the same time (init, for example).
- Logical — methods are "similar" (all start with
print_). Weak. - Coincidental — methods are in one class without a reason. Worst (god class).
Aim for functional. Everything below is a trap.
Symptoms of low cohesion
- An "and" in the class name or description:
OrderAndCustomerService. - Methods that do not use the same fields.
- A test needs complex setup for fields unrelated to what is being tested.
- Many imports from different areas (
smtplib,psycopg2,boto3,stripe). - The file grows past 300 lines with multi-topic code.
- Names like
Manager,Helper,Util,Servicewith no qualifier.
Low Coupling — external independence
What it is
The class knows about as few other classes as possible. Changing one class should not force edits in many others.
Six levels of coupling (worst to best)
| Type | What it is | Example | Bad / good |
|---|---|---|---|
| Content | One class modifies another's internals | other._private_field = x |
❌ worst |
| Common | Shared global mutable state | users_db: list = [] global |
❌ |
| External | A direct dependency on an external system | import requests; requests.get(...) inside |
❌ |
| Control | Passing a flag that controls behaviour | process(data, mode="parse") |
⚠️ |
| Stamp | Passing a complex structure when only part is used | func(user) when only user.email is needed |
⚠️ |
| Data | Passing exactly the parameters needed | func(email) |
✅ best |
Symptoms of high coupling
- "Train wrecks":
a.b.c.d.do_thing()— the class knows the internals of the chain. - Parameter explosions: methods with 7-10 parameters.
- Many imports: 15+
importstatements at the top of the file. - Changing one class = edits in 10 others.
- Tests need lots of mocks (5 per test).
- Global variables (
module_level = []). isinstancechecks on someone else's types.
Classic example: breaking up a god class
❌ Low cohesion, high coupling
class CustomerAccountManager:
def __init__(self, db, email_client, sms_client, payment_gateway, analytics):
self._db = db
self._email = email_client
self._sms = sms_client
self._payment = payment_gateway
self._analytics = analytics
# Profile
def get_profile(self, customer_id): ...
def update_profile(self, customer_id, name, email, phone): ...
# Orders
def list_orders(self, customer_id): ...
def cancel_order(self, customer_id, order_id, reason, notify, refund_now): ...
# Notifications
def send_welcome_email(self, customer_id): ...
def send_birthday_sms(self, customer_id): ...
# Billing
def charge_subscription(self, customer_id, amount): ...
def issue_refund(self, customer_id, amount): ...
# Analytics
def track_event(self, customer_id, event): ...
Cohesion: five topics in one class. Very low. Coupling: depends on five infrastructure pieces. Very high.
A test for cancel_order? You need mocks for email, sms, payment, analytics — all of them, even if cancel does not use them. Why? Because they are in the constructor.
✅ High cohesion + low coupling
class ProfileService: # one topic
def __init__(self, repo: CustomerRepository):
self._repo = repo
def get_profile(self, customer_id): ...
def update_profile(self, customer_id, name, email, phone): ...
class OrderService: # one topic
def __init__(self, repo: OrderRepository, notifier: Notifier, payment: PaymentGateway):
self._repo = repo
self._notifier = notifier
self._payment = payment
def list_orders(self, customer_id): ...
def cancel_order(self, request: CancelOrderRequest): ...
class NotificationService: # one topic
def __init__(self, email: EmailSender, sms: SmsSender):
...
def send_welcome(self, customer_id): ...
def send_birthday(self, customer_id): ...
class BillingService: # one topic
def __init__(self, payment: PaymentGateway):
...
def charge_subscription(self, customer_id, amount): ...
def issue_refund(self, customer_id, amount): ...
Now:
- High cohesion: each class is about one thing.
- Low coupling:
ProfileServicedepends only onCustomerRepository. - Testing
cancel_order: mock only what is needed (Order repo + Notifier + Payment), not the whole panel.
Refactor patterns: tools for low coupling
1. Parameter Object — for methods with a parameter explosion
# ❌ 8 parameters
def cancel_order(self, customer_id, order_id, reason, notify_customer,
refund_immediately, refund_amount, send_apology_email,
admin_override): ...
# ✅ Parameter Object
@dataclass(frozen=True)
class CancelOrderRequest:
customer_id: int
order_id: int
reason: str
notify_customer: bool = True
refund_immediately: bool = False
refund_amount: float | None = None
send_apology_email: bool = False
admin_override: bool = False
def cancel_order(self, request: CancelOrderRequest): ...
Why it lowers coupling: adding a field means changing the DTO, not method signatures. Callers are not affected.
2. Hide Delegate — for train wrecks
# ❌ Train wreck — the client knows four levels
shipping_cost = order.customer.address.country.shipping_rate * order.weight
# ✅ Hide Delegate
class Order:
def shipping_cost(self) -> float:
return self._customer.country_shipping_rate() * self._weight
# customer knows about its address; we do not need to reach into it
Why it lowers coupling: the client knows only Order. It does not know about Customer, Address, Country.
This is the Law of Demeter ("talk only to your immediate friends, not your friends' friends").
3. Introduce Polymorphism, Pure Fabrication, Indirection — a mediator between two sides
# ❌ Direct dependency
class OrderService:
def __init__(self, postgres, stripe, sendgrid, ...): # knows everything
...
# ✅ Through intermediaries (Protocols)
class OrderService:
def __init__(self, repo: OrderRepository, payment: PaymentGateway, notifier: Notifier):
...
This is DIP from SOLID, viewed from a slightly different angle.
4. Extract Class — for low cohesion
If User has methods change_password, verify_email, manage_subscriptions, track_login_history, split into User, AuthService, SubscriptionManager, LoginTracker.
Anti-patterns
1. "Helper" / "Util" / "Manager" with everything
class UserUtils:
def hash_password(self, pw): ...
def format_name(self, first, last): ...
def calculate_age(self, dob): ...
def send_email(self, to, body): ...
Logical cohesion — methods grouped only because they are "about users". Split by topic: PasswordHasher, NameFormatter, AgeCalculator, EmailService.
2. Classes that wrap globals
class DatabaseManager:
_instance = None
_connection = None
@classmethod
def execute(cls, query): ...
Common coupling through a global. Every caller of DatabaseManager.execute(...) shares one connection. Tests become interdependent.
3. Control flags
def process_data(data, mode: str):
if mode == "parse": return _parse(data)
elif mode == "validate": return _validate(data)
elif mode == "transform": return _transform(data)
Control coupling: the caller drives the internals with a string. This is an OCP violation plus low cohesion (three functions in one). Split them.
4. "Stamp" — passing the whole thing when you need a piece
def send_welcome(user: User): # User with 30 fields
smtp.send(user.email, f"Hello {user.name}")
send_welcome only needs email and name. But it takes the whole User. Now send_welcome depends on the User shape — any change to User can affect it.
def send_welcome(email: str, name: str): # ← Data coupling, minimal
smtp.send(email, f"Hello {name}")
Now send_welcome depends only on two strings. It can be called without a User (in scripts, in tests).
High Cohesion ≠ one method per class
Over-splitting is also an anti-pattern:
class PasswordHasher:
def hash(self, pw): ...
class PasswordValidator:
def validate(self, pw): ...
class PasswordChanger:
def change(self, user, new_pw): ...
class PasswordResetTokenGenerator:
def generate(self, user): ...
Four classes on the password topic can be justified if these parts really evolve independently. Often, though, all four together make up a PasswordService with functional cohesion.
Pragmatic rule: one class = one family of methods that change together. Not "one class = one method".
Low Coupling ≠ zero connections
If a class is not connected to anything, it is useless. Coupling is needed. The question is what kind:
- Data coupling (pass the minimum) — best.
- Through Protocols (DIP) — second best.
- Through concrete classes (no Protocol) — acceptable in small systems.
- Through shared state (global) — bad.
- Through direct access to internals — worst.
Cohesion and Coupling: relationship to other principles
| Principle | How it relates |
|---|---|
| SRP | A class with one responsibility naturally has high cohesion |
| DIP | Dependence through abstractions equals low coupling |
| OCP | Editing only one class for a new feature is a consequence of high cohesion + low coupling |
| Information Expert | Cohesion is achieved when data and behaviour live together |
| Law of Demeter | A direct result of low coupling |
| Composition > inheritance | Composition gives lower coupling than inheritance |
Rules of thumb
- "And" in the class description = low cohesion. Split it.
- A method with more than 5 parameters is a candidate for Parameter Object.
- A chain
a.b.c.dis a candidate for Hide Delegate. - A test needing more than 3 mocks suggests too much coupling.
Helper/Util/Managerwithout a qualifier — suspicious names.- A
Userwith 30 fields plus a service that takes the wholeUserbut uses two of them —send(email, name)is better. - Global mutable variables are almost always bad coupling.
- If changing X means editing 5+ classes, coupling is too high.
One-line summary
Keep close things close (cohesion), keep distant things distant (coupling). If the boundaries are right, both principles fall out together with no effort.