Patterncore
Insider Trading
Also called inappropriate intimacy.
A code smell: two modules read and change each other's internal data, so neither can change without the other, and the coupling between them is hidden from the rest of the program.
- Family
- code-smell
- Intent
- Find the modules that reach into each other's internals, and move the shared data and behaviour so that each module talks to the other through a small, visible interface.
- Also called
- Inappropriate Intimacy
Intent
Find the pairs of modules that know too much about each other: one reads the other's private fields, or changes its data directly, or depends on the order in which the other does its work. Move the data and the behaviour so that each piece lives in one module, and let the other module use a small interface that the reader can see.
Problem
Modules must share some data, or they could not work together. The question is how they share it. A module that calls a function of another module through its public interface depends on that interface. A module that reads and writes the other module's internal fields depends on all of its internals, and the other module cannot change its representation without breaking it.
The second edition of Refactoring names the smell after a market crime: modules that trade data behind each other's backs. It asks the programmer to keep such trade to a minimum and to make the rest of it visible.1
The idea is older than the smell. Wikipedia defines coupling as "the degree of interdependence between software modules", and notes that "Low coupling often correlates with high cohesion, and vice versa."2 The strongest kind on its list is content coupling, when one module uses the internals of another, which "violates information hiding".2
The forces are these:
- Reaching into another module is the shortest path to a feature. A getter or a public field is already there.
- Two modules that grew up together often share data because their authors shared a mental model. Each change to one is then a change to both.
- The coupling is invisible from outside. A reader of the module's interface does not see that another module reads its fields.
- Inheritance makes it easier. A subclass can see and depend on the fields of its parent, and a parent can come to depend on what its subclasses do.
Solution
Refactoring gives a set of moves.1 The catalogue at refactoring.com has a card for each refactoring.3
- Put the data with its user: Move Function and Move Field. If one module uses the other's data more than its own, move the data or the function so that both are in one module.
- Give the shared part a home: if the two modules have a common interest, extract that interest into a third module, which both use through its interface.
- Put a module in the middle: Hide Delegate. Let one module act as the intermediary, so the client does not reach through it into a third.
- Break the inheritance: Replace Subclass with Delegate or Replace Superclass with Delegate, when a subclass and its parent depend on each other's internals.
The first edition gives the same moves under the name Inappropriate Intimacy, and adds two more: change a two-way link between classes into a one-way link, and use Extract Class for the common part.4
Example
A billing module computes an invoice. It reads the account's private list of payments and writes the account's balance directly. The account cannot change how it stores payments, and its balance can be out of step with its payments if billing forgets a step.
import assert from "node:assert/strict";
// Before: billing reads and writes the account's internals.
class AccountBefore {
constructor() {
this._payments = [];
this._balance = 0;
}
}
function payBefore(account, cents) {
account._payments.push({ cents });
account._balance -= cents;
}
function invoiceBefore(account, chargedCents) {
account._balance += chargedCents;
const paid = account._payments.reduce((t, p) => t + p.cents, 0);
return { charged: chargedCents, paid, due: account._balance };
}
// After: the account owns its data and offers three operations.
class Account {
#payments = [];
#charges = [];
pay(cents) {
this.#payments.push(cents);
}
charge(cents) {
this.#charges.push(cents);
}
get paid() {
return this.#payments.reduce((t, c) => t + c, 0);
}
get due() {
return this.#charges.reduce((t, c) => t + c, 0) - this.paid;
}
}
function invoice(account, chargedCents) {
account.charge(chargedCents);
return { charged: chargedCents, paid: account.paid, due: account.due };
}
const before = new AccountBefore();
const after = new Account();
payBefore(before, 1500);
after.pay(1500);
assert.deepEqual(invoice(after, 4000), invoiceBefore(before, 4000));
assert.deepEqual(invoice(after, 1000), { charged: 1000, paid: 1500, due: 3500 });
assert.equal(Object.keys(after).length, 0); // no field is visible from outside
console.log("invoice: tests pass");
invoice: tests pass
In the second version the account keeps its payments and charges in private fields, and the balance is computed from them, so it cannot be out of step. Billing calls charge, paid and due. The account can change how it stores the data, for example to one list of entries, and billing does not change.
| Language | What the example shows |
|---|---|
| JavaScript | private fields and three operations, as above |
| Python | the same account, with the internals behind methods and properties |
| Java | a subclass that reads its parent's protected list, replaced by a delegate |
| Go | an account type with unexported fields and exported methods |
# Before: billing reads and writes the account's internals.
class AccountBefore:
def __init__(self):
self._payments = []
self._balance = 0
def pay_before(account, cents):
account._payments.append(cents)
account._balance -= cents
def invoice_before(account, charged):
account._balance += charged
return {"charged": charged, "paid": sum(account._payments), "due": account._balance}
# After: the account owns its data and offers three operations.
class Account:
def __init__(self):
self._payments = []
self._charges = []
def pay(self, cents):
self._payments.append(cents)
def charge(self, cents):
self._charges.append(cents)
@property
def paid(self):
return sum(self._payments)
@property
def due(self):
return sum(self._charges) - self.paid
def invoice(account, charged):
account.charge(charged)
return {"charged": charged, "paid": account.paid, "due": account.due}
before = AccountBefore()
after = Account()
pay_before(before, 1500)
after.pay(1500)
assert invoice(after, 4000) == invoice_before(before, 4000)
assert invoice(after, 1000) == {"charged": 1000, "paid": 1500, "due": 3500}
print("invoice: tests pass")
invoice: tests pass
- Python has no private fields. A leading underscore is a convention that says "internal", and the smell in the first version is code outside the class that ignores it.
paidanddueare properties, so billing reads them like fields, but the account computes them from its own data and can change how it stores that data.
import java.util.ArrayList;
import java.util.List;
public class Main {
// Before: the subclass reads its parent's protected list.
static class AccountBefore {
protected final List<Integer> payments = new ArrayList<>();
protected int charged;
void pay(int cents) { payments.add(cents); }
void charge(int cents) { charged += cents; }
int due() { return charged - payments.stream().mapToInt(Integer::intValue).sum(); }
}
static class RewardsAccountBefore extends AccountBefore {
int points() { return payments.stream().mapToInt(c -> c / 100).sum(); }
}
// After: the account keeps its data private and tells a delegate about each payment.
interface Rewards {
void onPayment(int cents);
int points();
}
static final class PointPerDollar implements Rewards {
private int points;
public void onPayment(int cents) { points += cents / 100; }
public int points() { return points; }
}
enum NoRewards implements Rewards {
INSTANCE;
public void onPayment(int cents) {}
public int points() { return 0; }
}
static final class Account {
private final List<Integer> payments = new ArrayList<>();
private int charged;
private final Rewards rewards;
Account(Rewards rewards) { this.rewards = rewards; }
Account() { this(NoRewards.INSTANCE); }
void pay(int cents) {
payments.add(cents);
rewards.onPayment(cents);
}
void charge(int cents) { charged += cents; }
int due() { return charged - payments.stream().mapToInt(Integer::intValue).sum(); }
int points() { return rewards.points(); }
}
static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
RewardsAccountBefore before = new RewardsAccountBefore();
Account after = new Account(new PointPerDollar());
Account plain = new Account();
for (int c : List.of(1500, 250, 999)) {
before.pay(c);
after.pay(c);
plain.pay(c);
}
before.charge(4000);
after.charge(4000);
plain.charge(4000);
check(after.due() == before.due() && after.due() == 1251, "due");
check(after.points() == before.points() && after.points() == 26, "points");
check(plain.points() == 0 && plain.due() == 1251, "plain");
System.out.println("invoice: tests pass");
}
}
invoice: tests pass
- In the first version
paymentsisprotected, so the subclass depends on the parent's choice of aList<Integer>. A change to that field breaks the subclass. - In the second version the fields are
privateand the class isfinal. The rewards rule gets each payment throughonPayment, which is the only thing it knows about the account. - This is Replace Subclass with Delegate. An account can also change its rewards rule at run time by taking a different delegate, which a subclass cannot do.
package main
import "fmt"
// Before: billing reads and writes the account's fields.
type accountBefore struct {
Payments []int
Balance int
}
func payBefore(a *accountBefore, cents int) {
a.Payments = append(a.Payments, cents)
a.Balance -= cents
}
type bill struct{ charged, paid, due int }
func invoiceBefore(a *accountBefore, charged int) bill {
a.Balance += charged
paid := 0
for _, p := range a.Payments {
paid += p
}
return bill{charged, paid, a.Balance}
}
// After: unexported fields, exported methods. Outside this package only the methods are visible.
type Account struct {
payments []int
charges []int
}
func sum(xs []int) int {
t := 0
for _, x := range xs {
t += x
}
return t
}
func (a *Account) Pay(cents int) { a.payments = append(a.payments, cents) }
func (a *Account) Charge(cents int) { a.charges = append(a.charges, cents) }
func (a *Account) Paid() int { return sum(a.payments) }
func (a *Account) Due() int { return sum(a.charges) - a.Paid() }
func invoice(a *Account, charged int) bill {
a.Charge(charged)
return bill{charged, a.Paid(), a.Due()}
}
func main() {
before := &accountBefore{}
after := &Account{}
payBefore(before, 1500)
after.Pay(1500)
if invoice(after, 4000) != invoiceBefore(before, 4000) {
panic("first invoice")
}
if got := invoice(after, 1000); got != (bill{1000, 1500, 3500}) {
panic(fmt.Sprint("second invoice ", got))
}
fmt.Println("invoice: tests pass")
}
invoice: tests pass
- Go controls visibility by the case of the first letter, and the unit of visibility is the package, not the type. In one file, as here,
maincould still reada.payments. The protection is real whenAccountis in its own package. - A struct value of type
billcan be compared with==because all its fields are comparable, so the test compares whole invoices.
Consequences
Each module owns its data, and the trade between modules goes through an interface that a reader can see. A change inside one module stays inside it, and a test of one module needs fewer details of the other.
The interface has a cost. Each operation that the other module needs is one more method, and a careless fix can turn every field into a getter and a setter, which keeps the coupling and only hides it. The aim is fewer and larger operations that say what the client wants, as charge does here.
Some modules belong together. Two classes that always change together and share most of their data may be one module, and the fix is to merge them, not to build an interface between them. Languages give tools for a close pair: a nested class in Java, unexported names shared inside one package in Go, a module-level function in Python. These keep the closeness local, where a reader can see it.
How to fix it
- A function that uses another module's data more than its own: Move Function.1
- A field that another module reads and writes more than its owner: Move Field.1
- Two modules with a common interest: a third module for it, which both use.1
- A client that reaches through one module into another: Hide Delegate.1
- A subclass and a parent that depend on each other's internals: Replace Subclass with Delegate or Replace Superclass with Delegate.1
Variants and related patterns
Feature Envy. One function that uses another module's data more than its own. Insider Trading is the same problem between whole modules, often in both directions. See Feature Envy.
Global Data. Data that every module can read and write is a trade with no owner at all. See Global Data.
Composition over inheritance. Replacing a subclass with a delegate turns a close link into one through an interface. See Composition over inheritance.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Insider Trading
- Wikipedia, Coupling (computer programming), revision 1367462368, the introduction, Coupling and cohesion, and Content coupling
- Martin Fowler, Catalog of Refactorings, the cards Move Function, Move Field, Hide Delegate, Replace Subclass with Delegate and Replace Superclass with Delegate
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Inappropriate Intimacy
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EA9FF9 Edit this page History Report an error Markdown