# Inappropriate IntimacyTeam 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.

{{< lesson-video youtube="IFDesXPwUWY" title="Inappropriate Intimacy" >}}

## Two classes, one broken roster

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.

## Neighbours with keys

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](https://refactoring-assistant.github.io/couplers/inappropriate-intimacy)
defines it the same way: a class that uses the internal fields and methods of another class
directly.

## The naive version

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:

```java
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:

```java
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.)

## Why it hurts

Now the league wants shirt numbers. So the roster becomes a map, keyed by number:

```java
// 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.

```mermaid {alt="Before and after. Before: Team edits Player's stats directly and Player adds itself to Team's public roster, two arrows in opposite directions. After: Team asks Player to record a game through one method call, a single arrow." caption="Two-way reaching becomes a one-way call."}
flowchart LR
  subgraph after["After: knocking"]
    direction TB
    T2["Team"] -->|"p.recordGame(goals)"| P2["Player"]
  end
  subgraph before["Before: walking in"]
    direction TB
    T1["Team"] -->|"edits p.stats"| P1["Player"]
    P1 -->|"t.roster.add(this)"| T1
  end
  class T1,P1 bad
  class T2,P2 good
```

## How to spot it

1. **One class reads or writes another class's public fields.**
2. **Two classes hold pointers to each other.**
3. **A change inside one class stops the other from compiling.**
4. **A method touches more of another class's data than its own.** That's
   [Feature Envy](/code-smells/feature-envy/), one half of the same problem.

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.

## The key insight: knock, don't walk in

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](/fundamentals/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: Move Field and Move Method

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.)

```java
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.

## The fix: one-way links and extracted classes

**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:

```java
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`:

```java
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.

```mermaid {alt="Class diagram after the refactoring. Team holds a private roster and offers signPlayer, recordGame and roster. RosterMembership holds a player and a shirt number. Player owns goals and games with recordGame and goalsPerGame. Captain holds a Player and delegates to it. Team points to RosterMembership, RosterMembership points to Player, and Captain points to Player." caption="Every arrow now goes through a method."}
classDiagram
  class Team {
    -roster list
    +signPlayer(Player) void
    +recordGame(Player, int) void
    +roster() list
  }
  class RosterMembership {
    -shirtNumber int
    +player() Player
    +shirtNumber() int
  }
  class Player {
    -goals int
    -games int
    +recordGame(int) void
    +goalsPerGame() double
  }
  class Captain {
    -captainGames int
    +recordGame(int) void
  }
  Team --> RosterMembership : holds
  RosterMembership --> Player : refers to
  Captain --> Player : delegates to
```

## A second example: the captain

The same smell hides in inheritance. A captain extends a player, and reaches into its protected
fields to count games:

```java
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:

```java
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.

## Commonly confused: Data Class and Feature Envy

Inappropriate intimacy has partners. [Data Class](/code-smells/data-class/) is the class that
gets walked into. [Feature Envy](/code-smells/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.

```mermaid {alt="Three related smells. Feature Envy, a method that walks into another class, and Data Class, the class that gets walked into, both feed into Inappropriate Intimacy, where both classes walk into each other. The shared fixes are Move Method, Move Field, Extract Class and Hide Delegate." caption="Three views of misplaced behavior, one set of moves."}
flowchart LR
  E["Feature Envy<br/>a method walks in"] --> I["Inappropriate Intimacy<br/>both classes walk in"]
  D["Data Class<br/>the class walked into"] --> I
  I --> M["Move Method, Move Field,<br/>Extract Class, Hide Delegate"]
  class E,D,I bad
  class M good
```

## Myths, and when to leave it

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.

```mermaid {alt="Decision flow. Does one class touch another's fields? If not, it is fine: talk through methods. If so, is the pair close on purpose, inside one package, an inner class, or a builder and its product? If yes, leave it. If not, do both sides point at each other? If yes, make the link one way or extract a class. If not, move the code to its owner and hide the field behind a method." caption="When to refactor, and when to leave it."}
flowchart TD
  A{"does one class touch<br/>another's fields?"}
  A -->|no| OK1["fine: talk through methods"]
  A -->|yes| B{"close on purpose?<br/>one package, inner class,<br/>builder and product"}
  B -->|yes| OK2["leave it"]
  B -->|no| C{"do both sides<br/>point at each other?"}
  C -->|yes| F1["make the link one way<br/>or extract a class"]
  C -->|no| F2["move the code to its owner<br/>hide the field"]
  class F1,F2 good
  class OK1,OK2 muted
```

## Recap

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.

```mermaid {alt="Recap chain: classes walk into each other; spot fields and two-way pointers; fix by moving, making links one way and extracting; partners are Data Class and Feature Envy." caption="Knock on the door. Don't walk in."}
flowchart LR
  A["classes walk<br/>into each other"] --> B["spot: fields and<br/>two-way pointers"] --> C["fix: move, one-way,<br/>extract"] --> D["partners: Data Class,<br/>Feature Envy"]
  class C good
```

Checklist:

- Does any class read or write another class's public fields?
- Do two classes hold pointers to each other?
- Does a change in one class break the other?
- Does a subclass touch its parent's fields?
- Is the closeness deliberate, inside one module? If so, leave it.

> **Knock on the door. Don't walk in.**

## Further reading

- [Inappropriate Intimacy](https://refactoring-assistant.github.io/couplers/inappropriate-intimacy), the course's Code Smells Reference.
- [Inappropriate Intimacy](https://refactoring.guru/smells/inappropriate-intimacy) on refactoring.guru.
- Fowler's refactoring catalog: [Move Field](https://refactoring.com/catalog/moveField.html),
  [Move Function](https://refactoring.com/catalog/moveFunction.html) (Move Method),
  [Extract Class](https://refactoring.com/catalog/extractClass.html),
  [Hide Delegate](https://refactoring.com/catalog/hideDelegate.html),
  [Replace Superclass with Delegate](https://refactoring.com/catalog/replaceSuperclassWithDelegate.html).
