November 26, 20268 minutes
Team and Player reach into each other, and a small change to the roster breaks Player. Learn to spot Inappropriate Intimacy and fix it, and when close classes are fine.
A sports league app has two classes, a team and a player. They work closely together, and that’s fine. The trouble is how. The team edits the player’s stats directly, reaching into its field. And the player adds itself to the team’s roster, which is a public list. Each one keeps a pointer to the other. Now change how the roster is stored, and the player stops working. Why does a change in one class break the other? That’s a smell called Inappropriate Intimacy.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Keep the question in mind: why does a change in one class break the other? The answer is that
neither class stays on its own side of the line. Team knows how Player keeps its stats, and
Player knows how Team keeps its roster.
Picture two neighbours who each keep a key to the other’s house. They walk in whenever they like. One rearranges the other’s furniture. The other fills the shelves. It works, until one of them rearranges for good. Then the other comes home and can’t find the kettle.
Good neighbours knock. They ask, and the other person decides what to do.
The team and the player are the neighbours. The public fields are open side doors. The methods are the front door. A class should know as little about its neighbours as possible, and walking in is the smell. The course reference page defines it the same way: a class that uses the internal fields and methods of another class directly.
Here’s the team. Its roster is a public list, and signing a player sets the player’s team field from outside. Recording a game reaches into the player’s stats and bumps the numbers itself:
class Team {
public List<Player> roster = new ArrayList<>();
void signPlayer(Player p) {
p.team = this;
roster.add(p);
}
void recordGame(Player p, int goals) {
p.stats.goals += goals;
p.stats.games++;
}
}And here’s the player, with a stats class that is just two public numbers. Its team and stats fields are public, and joining a team adds itself to the roster:
class Stats { public int goals; public int games; }
class Player {
public Team team;
public Stats stats = new Stats();
void joinTeam(Team t) {
this.team = t;
t.roster.add(this);
}
}Why write it this way? Public fields are the easy way, and it works, because each class knows how the other stores things. (The course page names that as the usual cause: touching a public field is easier than writing a getter and a setter.)
Now the league wants shirt numbers. So the roster becomes a map, keyed by number:
// Team: the roster becomes a map by shirt number
public Map<Integer, Player> roster = new HashMap<>();
// Player.joinTeam: no longer compiles
t.roster.add(this);The team compiles. The player doesn’t, because it called add on a list that’s gone. In a bigger
app, every class that touched the roster list would break the same way.
There are two more costs. The stats rule lives in the team, so the player can’t protect its own numbers. And you can’t test one class without building the other. A change ripples, a rule is scattered, and neither class can stand alone.
On a class diagram, two arrows between the same pair of classes are a hint. Check whether both are really needed, and whether either class could stay ignorant of the other.
So how close is too close? Classes can collaborate as much as they like, as long as they talk
through behavior. Ask for what you need through a method. Don’t reach for the field behind it:
p.recordGame(goals), not p.stats.goals += goals.
A method is a promise. The player promises to record a game, and keeps the freedom to count however it likes. That freedom is what Encapsulation protects. The course page puts the goal plainly: classes should know as little about each other as possible.
Knock on the door. Don’t walk in.
The fix takes three moves. First, Move Field and Move Method. The stats are the player’s own numbers, so the recording rule moves into the player, and the fields go private. (The course page calls that last part Hide Delegate: the field sits behind methods.)
class Player {
private int goals;
private int games;
void recordGame(int goals) {
this.goals += goals;
this.games++;
}
double goalsPerGame() {
return games == 0 ? 0 : (double) goals / games;
}
}Check one thing before you move a member: does the original class still need it? If not, move it. If it does, think again. Now the team just says: record this game. How the player counts is the player’s business. And the player can answer new questions, like goals per game.
Second, Change Bidirectional Association to Unidirectional. Does the player need to know its team? Almost never. So drop that pointer, and let the team own the roster:
class Team {
private final List<Player> roster = new ArrayList<>();
void signPlayer(Player p) {
roster.add(p);
}
void recordGame(Player p, int goals) {
p.recordGame(goals);
}
List<Player> roster() {
return List.copyOf(roster);
}
}The team keeps its list private and hands out a read-only copy (List.copyOf). Change how it’s
stored, and nobody else notices. What if both sides truly need each other? Then keep one class in
charge: one method updates both pointers, so the two never disagree.
Third, Extract Class. Sometimes the link has data of its own, like a shirt number. That belongs
to neither side, so give it a class, RosterMembership:
class RosterMembership {
private final Player player;
private final int shirtNumber;
RosterMembership(Player player, int shirtNumber) {
this.player = player;
this.shirtNumber = shirtNumber;
}
Player player() { return player; }
int shirtNumber() { return shirtNumber; }
}
// in Team
void sign(Player p, int shirtNumber) {
roster.add(new RosterMembership(p, shirtNumber));
}Now the team holds memberships, and the player knows nothing about teams at all.
The same smell hides in inheritance. A captain extends a player, and reaches into its protected fields to count games:
class Captain extends Player {
int captainGames;
@Override
void recordGame(int goals) {
this.games++;
this.goals += goals;
this.captainGames++;
}
}(This assumes Player’s fields are protected.) If the player changes how it counts, the captain
breaks, or counts twice. A subclass is the closest neighbour of all: it lives in the parent’s house.
So replace inheritance with delegation. The captain holds a player, and calls its methods:
class Captain {
private final Player player;
private int captainGames;
Captain(Player player) { this.player = player; }
void recordGame(int goals) {
player.recordGame(goals);
captainGames++;
}
}Now the captain adds its own count, and the player’s rules stay in the player. Fowler’s catalog lists this move as Replace Superclass with Delegate (alias Replace Inheritance with Delegation). The course page shows a coffee machine that goes the other way: when the association is the wrong shape and inheritance fits, you Replace Delegate with Inheritance. The goal is the right shape, not one fixed rule.
Inappropriate intimacy has partners. Data Class is the class that gets walked into. Feature Envy is a method that walks in. Intimacy is the pair seen from both sides, with each class walking into the other.
The same few moves fix all three: Move Method, Move Field, Extract Class, and hiding the field behind a method. So when you find one of the three, look for the other two. Fixing the pair together beats patching one side.
One myth to drop: that any two classes working closely together are too intimate. Collaboration through methods is normal. The smell is reaching into private state. The methods are the front door.
Some pairs are close on purpose, so leave them alone: classes in one small package, an inner class and its outer class, a builder and its product. Closeness is also a matter of scale. An inner class can see its outer class’s private members by design (the Java Language Specification allows it, §6.6.1), and the two ship together. Keep that closeness inside one module, and make sure it’s on purpose. The course page lists no exceptions, so this part is our own judgment.
Inappropriate intimacy is two classes that know each other’s insides. Spot it by public fields and pointers both ways. Fix it by moving the code to its owner, making the link one way, and extracting what they share. And remember its partners: data class and feature envy.
Checklist:
Knock on the door. Don’t walk in.