Inappropriate intimacy is when two classes spend more time inside each other than inside themselves. One reads the other's fields directly, changes its state without asking, and depends on details that should be private. Often the traffic runs in both directions, so neither class can change without the other changing too. The damage is quiet. Each class looks small and harmless on its own, but the rules that govern their shared data are split across both files. Nobody owns the invariant, so sooner or later the two halves disagree. In interviews, this smell is a good way to show that you think about encapsulation as a question of who owns which rule, not just of making fields private.
Signs
How to spot it in a review.
- Class A assigns to fields of class B (
b.status = ...,b.balance -= ...) instead of calling a method that B controls. - Both classes hold references to each other, and each one walks into the other to read or mutate state.
- A business rule about one object's data, such as pricing or a state transition, is implemented in a different class.
- Changing a field name or type in one class forces edits in the other, even though the behaviour did not change.
- Fields are made public, or getters and setters are added, only so the partner class can manipulate them.
- Tests for one class have to build and inspect the internals of the other to check the result.
What it looks like
A typical case, in three languages.
class MemberAccount {
bookings: DeskBooking[] = [];
constructor(
public readonly memberId: string,
public creditMinutes: number,
public tier: "basic" | "pro",
) {}
cancelAll(): number {
let refunded = 0;
for (const booking of this.bookings) {
if (booking.status === "confirmed") {
booking.status = "cancelled";
refunded += booking.minutes;
}
}
this.creditMinutes += refunded;
return refunded;
}
}
class DeskBooking {
status: "pending" | "confirmed" | "cancelled" = "pending";
constructor(
public readonly deskId: string,
public readonly minutes: number,
private readonly account: MemberAccount,
) {}
confirm(): void {
const cost =
this.account.tier === "pro" ? Math.ceil(this.minutes * 0.8) : this.minutes;
if (this.account.creditMinutes < cost) {
throw new Error(`Member ${this.account.memberId} lacks credit for desk ${this.deskId}`);
}
this.account.creditMinutes -= cost;
this.account.bookings.push(this);
this.status = "confirmed";
}
}
const account = new MemberAccount("m-311", 600, "pro");
new DeskBooking("D-14", 240, account).confirm();
new DeskBooking("D-02", 90, account).confirm();
console.log(account.creditMinutes); // 336
console.log(account.cancelAll()); // 330
console.log(account.creditMinutes); // 666import math
class MemberAccount:
def __init__(self, member_id: str, credit_minutes: int, tier: str):
self.member_id = member_id
self.credit_minutes = credit_minutes
self.tier = tier
self.bookings: list["DeskBooking"] = []
def cancel_all(self) -> int:
refunded = 0
for booking in self.bookings:
if booking.status == "confirmed":
booking.status = "cancelled"
refunded += booking.minutes
self.credit_minutes += refunded
return refunded
class DeskBooking:
def __init__(self, desk_id: str, minutes: int, account: MemberAccount):
self.desk_id = desk_id
self.minutes = minutes
self.account = account
self.status = "pending"
def confirm(self) -> None:
cost = math.ceil(self.minutes * 0.8) if self.account.tier == "pro" else self.minutes
if self.account.credit_minutes < cost:
raise ValueError(
f"Member {self.account.member_id} lacks credit for desk {self.desk_id}"
)
self.account.credit_minutes -= cost
self.account.bookings.append(self)
self.status = "confirmed"
account = MemberAccount("m-311", 600, "pro")
DeskBooking("D-14", 240, account).confirm()
DeskBooking("D-02", 90, account).confirm()
print(account.credit_minutes) # 336
print(account.cancel_all()) # 330
print(account.credit_minutes) # 666<?php
class MemberAccount
{
/** @var DeskBooking[] */
public array $bookings = [];
public function __construct(
public readonly string $memberId,
public int $creditMinutes,
public string $tier,
) {}
public function cancelAll(): int
{
$refunded = 0;
foreach ($this->bookings as $booking) {
if ($booking->status === 'confirmed') {
$booking->status = 'cancelled';
$refunded += $booking->minutes;
}
}
$this->creditMinutes += $refunded;
return $refunded;
}
}
class DeskBooking
{
public string $status = 'pending';
public function __construct(
public readonly string $deskId,
public readonly int $minutes,
private readonly MemberAccount $account,
) {}
public function confirm(): void
{
$cost = $this->account->tier === 'pro'
? (int) ceil($this->minutes * 0.8)
: $this->minutes;
if ($this->account->creditMinutes < $cost) {
throw new RuntimeException(
"Member {$this->account->memberId} lacks credit for desk {$this->deskId}"
);
}
$this->account->creditMinutes -= $cost;
$this->account->bookings[] = $this;
$this->status = 'confirmed';
}
}
$account = new MemberAccount('m-311', 600, 'pro');
(new DeskBooking('D-14', 240, $account))->confirm();
(new DeskBooking('D-02', 90, $account))->confirm();
echo $account->creditMinutes, PHP_EOL; // 336
echo $account->cancelAll(), PHP_EOL; // 330
echo $account->creditMinutes, PHP_EOL; // 666This is a coworking app's credit system. DeskBooking.confirm decides the pro discount, debits the account's balance and appends itself to the account's list. MemberAccount.cancelAll flips each booking's status and refunds full minutes. Because charging lives in one class and refunding in the other, they disagree: the member paid 264 minutes but gets 330 back, ending with 666 instead of 600. Fix it by moving the charge and refund into MemberAccount, and the status transitions into DeskBooking methods like markConfirmed and cancel, storing the charged amount on the booking.
Why it happens
How code ends up like this.
- Rules about a piece of data end up split across two files, so a change to one half (like adding a discount) silently skips the other half (the refund).
- Neither class can protect its invariants, because the other one writes to its fields directly. Any bug in A can corrupt B's state.
- You cannot change the internal representation of either class, such as storing credit in cents or making status an enum, without editing both.
- The pair is effectively one class split in two, but without the cohesion of one, so reading either file gives you only half the story.
- Testing in isolation becomes impossible: every test needs a fully wired partner object, and assertions have to inspect someone else's fields.
Treatment
The refactorings that cure it, and when to choose each.
- Move Function: Put Behaviour Next to the Data It Uses
A method mostly works on another class's data, like
confirmdebiting the account. Move it to the class that owns the data, soMemberAccount.charge(booking)holds both pricing and balance changes. - Change Function Declaration: Fix a Signature Without Breaking Callers
Once logic has moved, replace direct field writes with intention-revealing methods such as
booking.cancel()oraccount.refund(minutes), then make the fields private or read-only. - Extract Class: Split a Class That Does Two Jobs
The two classes share a cluster of state that belongs to neither, such as a credit ledger with charges and refunds. Pull it into its own class that both talk to through a narrow interface.
- Hide Delegate: Stop Callers Reaching Through an Object's Internals
Callers reach through one object to manipulate another (
booking.account.bookings.push). Add a method on the nearer object so the chain and the internal list stay hidden. - Inline Class: Fold a Class That No Longer Earns Its Keep
After moving functions, one class is left with almost no behaviour of its own and exists only to hold fields for the other. Merge them into one cohesive class.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
The shared data is a raw number or string, like credit minutes or a status string. Wrapping it in a value object gives the rules a single home that both classes can use without poking at each other.
Payoff
What you get once it's gone.
- Each invariant has one owner, so bugs like the refund mismatch cannot appear from rules drifting apart.
- You can change a class's internal fields without touching its partner, as long as its public methods keep their contract.
- Classes become testable alone: you assert on return values and public state, not on another object's private fields.
- Code reads by intent, since
account.refund(booking)explains what happens whereaccount.creditMinutes += xdoes not.
When to leave it
Sometimes it's not worth fixing.
- Inside a single module, a small helper class designed as an implementation detail of one public class, like a node type inside a tree, can share data with its owner without much risk.
- Plain data structures with no behaviour, such as DTOs or records passed between layers, are meant to be read directly. Intimacy matters when both sides carry rules.
- Language features built for tight pairing, like nested or friend classes in some languages, can be acceptable when the coupling is deliberate, documented and contained.
Common questions
Short answers to the usual doubts.
How is inappropriate intimacy different from feature envy?
Feature envy is one method that uses another class's data more than its own. Inappropriate intimacy is a relationship between two classes: they routinely access each other's internals, often in both directions. Feature envy is frequently the symptom you fix first; moving the envious methods with move-function is usually how you untangle intimate classes.
Is a bidirectional reference between two classes always this smell?
No. An account knowing its bookings and a booking knowing its account can be fine. The smell is in what they do with the reference. If each side only calls the other's public, intention-revealing methods, the coupling is honest. If they write each other's fields or replicate each other's rules, it is intimacy.
Does making fields private fix the problem?
Not on its own. If you make fields private and then add a getter and setter for each one, the partner class can still do exactly what it did before. The fix is to move the behaviour so that the class owning the data also owns the decisions about it, and to expose operations rather than raw state.
How should I talk about this smell in an interview?
Point to a concrete invariant that has no single owner, such as a balance that is charged in one class and refunded in another. Explain the bug it allows, then describe moving the logic to the data owner, exposing methods like charge and refund, and locking down the fields. That shows you reason about ownership, not just syntax.
Can inheritance create inappropriate intimacy?
Yes. A subclass that reaches into many protected fields of its parent and depends on the parent's internal call order is tightly coupled in the same way. Replacing the inheritance with delegation, or giving the parent a narrower set of protected methods, usually loosens it.