Encapsulation
The interface is the only contract. The implementation is a design secret.
Parnas wrote it down in 1972 and the wording has not aged: every module is characterised by its knowledge of a design decision which it hides from all others. Its interface is chosen to reveal as little as possible about its inner workings. That is the rule and it is the foundation that makes change cheap. A unit whose implementation is private can be rewritten without touching its callers. A unit whose implementation has leaked has fused itself to every callsite that knows about its insides.
Opinion
I've watched modern codebases pretend to follow F6 because the language provides the keywords. They have private fields, protected methods and exports with names on them. The syntactic surface looks encapsulated. The practice diverges. The class exposes a getter and setter for every private field, so the encapsulation is decoration. The module exports a helper a single caller uses, so the boundary is theatrical. The function takes a flag that lets the caller bypass an invariant, so the body is no longer a secret. The keyword is there. The discipline is not.
The pressure always runs the other way: more flexibility for the caller, more configurability, more introspection. Every one of those moves is easy to add and hard to remove: once a getter exists, callers find it and the implementation behind it is fixed forever. The fix is not more keywords. It is fewer affordances: the public surface is the smallest set of operations that lets callers do their job, and any state callers do not need to see is not reachable.
Agents read the public interface the same way reviewers do, which makes every leak more expensive, not less. If the implementation has leaked, the agent reads the leak and treats it as part of the contract. Within a session that may be benign. Across sessions and across teams the leak compounds into a structural dependency no-one notices until the body has to change. Encapsulation is the only practical defence against that compound: the linter floor is necessary, the review culture is what holds it up.
Copy a note and link
Grab this short comment and drop it into a PR comment or an LLM chat to prompt the right change.
Hide the inside of your code. Callers should only call methods: never read or change fields directly. If state has to change, give them a method that does it safely. Always mark every field and method as `public` or `private`; never rely on the language default. /tenet/encapsulation/F6
AI eyes only
Rule: the interface is the only contract. Public mutable state is a defect.
Reject: pairs of getters and setters that expose private fields. Reject: public mutable members. Reject: default-visibility on classes that hold state. Reject: returning internal collections by reference.
Generate: behavioural methods that operate on internal state and enforce invariants. Constructors that validate. private (or #-prefix) by default. Only promote to public when a caller demonstrates the need.
Diagnostic: if removing a public member would mean a single-line rename in callers, the member is leaking implementation. Replace with a behavioural method named for the operation.
Why?
- The body is free to change while the contract holds. The cost of a refactor is bounded to the unit, not its callers.
- The unit is testable through its interface alone. Encapsulation produces the boundary TS7 Test Isolation wants to mock at.
- Reviewers read the public surface to validate behaviour. They don't need to read the body. Smaller surfaces mean faster reviews.
- Behavioural subtyping (A9 LSP) only works when the contract is stable. F6 makes LSP enforceable. Without encapsulation, every subtype can be broken by a parent-class internals leak.
- Private mutable state is debuggable. Public mutable state is a race. Encapsulation is the cheapest form of concurrency safety we have.
- Pairs with T1 Domain-Driven Types: the type encodes the contract; encapsulation enforces that callers cannot construct invalid states by reaching into the body.
- Agent-generated code stays composable when the public surface is small. Implementation leaks turn into agent-encoded contracts that compound across sessions.
Origins
David Parnas wrote the foundational paper in 1972. On the Criteria to be Used in Decomposing Systems into Modules presented two decompositions of a single program (the KWIC index) and showed that the information hiding decomposition produced cheaper change, while the flowchart-based decomposition produced fragile code that propagated changes across modules. The argument has not been bettered: every module is characterised by its knowledge of a design decision which it hides from all others.1
Barbara Liskov extended the argument to types in 1987. The Liskov Substitution Principle is, at heart, an encapsulation rule: a subtype must honour the encapsulated promises of its supertype, or substitution silently breaks. LSP stops encapsulation being decorative by pushing the discipline into the type system rather than leaving it at the keyword level.2
Bertrand Meyer 1988 operationalised encapsulation as Design by Contract: pre- conditions, post-conditions, and class invariants are the executable form of the encapsulated interface. Eiffel made these first-class language constructs; TypeScript's readonly, Rust's ownership model, and modern type-state APIs are all descendants. Contracts make the body a secret you can trust.3
The Gamma, Helm, Johnson, Vlissides 1994 catalogue codified the practical lever: encapsulate what varies. Every behavioural pattern (Strategy, State, Command, Observer) is an encapsulation move, and every structural pattern (Adapter, Bridge, Facade, Proxy) is one too. The patterns are not arbitrary. They are twenty-three solutions to the same recurring problem of which design decisions to hide and how to hide them.4
Joshua Bloch 2018 ported the principle into modern Java idiom as Item 15: Minimize the accessibility of classes and members. The justification is Parnas's: information hiding decouples the components that comprise a system, allowing them to be developed, tested, optimised, used, understood, and modified in isolation. Forty-six years separate the two formulations. The rule is the same.5
Quotes
Every module in the second decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings.
Under the Design by Contract theory, a software system is viewed as a set of communicating components whose interaction is based on precisely defined specifications of the mutual obligations — contracts.
Program to an interface, not an implementation. … Favor object composition over class inheritance.
Information hiding is important for many reasons, most of which stem from the fact that it decouples the components that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation.
Evidence
15 external sources, ranked by author authority. The first five are the canon; expand to see the rest, including the qualifiers and the named opposers. Each links out to its primary source.
- 01The foundational paper. Information hiding as the criterion for decomposition. The KWIC example shows the cost of getting it wrong.
- 02Data Abstraction and HierarchySupportsBehavioural subtyping. Encapsulation enforced through types: a subtype must honour the supertype's encapsulated contract or substitution breaks.
- 03Design by Contract, preconditions, postconditions, invariants, is the executable form of the encapsulated interface.
- 04'Encapsulate what varies' is the catalogue's through-line. Every pattern is an encapsulation move.
- 05The modern Java textbook formulation. The rationale is Parnas's, undimmed by 46 years.
- 06Distinguishes objects (which encapsulate behaviour and hide state) from data structures (which expose state and have no behaviour). The chapter is essentially F6 as a Java textbook.
- 07Tell-Don't-Ask is the operational form of F6: methods over field access. Behaviour over state inspection.
- 08Tell, Don't Ask (bliki)SupportsShort essay reformulating the rule for the OO community. The pattern is encapsulation in two words.
- 09The canonical taxonomy treats Information Hiding and Encapsulation as a single principle with two names.
- 10Modern academic restatement. Important qualifier: Ousterhout argues that *deep modules*, small interfaces over substantial behaviour, are the operational target. Shallow modules with trivial encapsulation defeat the purpose.
- 11Safety-critical analogue: data must be declared at the smallest possible scope. F6 enforced by static analysis with zero-warning policy.
- 12Modern operationalisation: TypeScript supports both keyword visibility (public/private/protected) and JavaScript native #private fields. The latter is genuinely runtime-private.
- 13Formalisation of the 1987 keynote. Defines subtyping in terms of *behavioural compatibility*, the encapsulated contract, rather than syntactic structure.
- 14Inheritance leaks the parent's implementation into the subclass. Composition keeps each unit's body private. CRP is encapsulation applied to reuse.
- 15Parnas himself separates two properties: his information-hiding decomposition does yield a Dijkstra-style hierarchy, but he concludes that hierarchical structure and 'clean' decomposition are 'two desirable but independent properties of a system structure'. Hiding is not the same thing as layering.
Fifteen sources across five decades. The supporting line runs unbroken from Parnas in 1972 through Liskov, Meyer, GoF, and Bloch. The qualifying voice extends rather than challenges: shallow modules with trivial encapsulation are no improvement over leaks. The operational target is deep modules with substantial behaviour behind narrow interfaces. The corpus has no opposing line. Encapsulation is the most stable principle in the Foundations.
Examples
Before callers maintain the invariant by hand. One forgets and total drifts.
class ShoppingCart { items: Item[] = []; total: number = 0; }
checkout.tscaller code, scattered across filescart.items.push(item); cart.total += item.price;
gift-basket.tselsewhere, the second caller forgetsotherCart.items.push(item); // total now lies
After state is private; the invariant lives inside the unit.
class ShoppingCart { private readonly items: Item[] = []; private total = 0; public add(item: Item): void { this.items.push(item); this.total += item.price; } public getTotal(): number { return this.total; } }
checkout.tsthe invariant cannot driftcart.add(item);
Before callers maintain the invariant by hand. One forgets and total drifts.
class ShoppingCart { items: Item[] = []; total: number = 0; }
checkout.tscaller code, scattered across filescart.items.push(item); cart.total += item.price;
gift-basket.tselsewhere, the second caller forgetsotherCart.items.push(item); // total now lies
After state is private; the invariant lives inside the unit.
class ShoppingCart { private readonly items: Item[] = []; private total = 0; public add(item: Item): void { this.items.push(item); this.total += item.price; } public getTotal(): number { return this.total; } }
checkout.tsthe invariant cannot driftcart.add(item);
Before callers maintain the invariant by hand. One forgets and total drifts.
class ShoppingCart { constructor() { this.items = []; this.total = 0; } } cart.items.push(item); cart.total += item.price; // drift waiting to happen
After state is private; the invariant lives inside the unit.
class ShoppingCart { #items = []; #total = 0; add(item) { this.#items.push(item); this.#total += item.price; } getTotal() { return this.#total; } }
Before callers maintain the invariant by hand. One forgets and total drifts.
class ShoppingCart: def __init__(self): self.items: list = [] self.total: float = 0.0
checkout.pycart.items.append(item) cart.total += item.price
After state is private; the invariant lives inside the unit.
class ShoppingCart: def __init__(self): self._items: list = [] self._total: float = 0.0 def add(self, item: Item) -> None: self._items.append(item) self._total += item.price @property def total(self) -> float: return self._total
Before callers maintain the invariant by hand. One forgets and total drifts.
public class ShoppingCart { public List<Item> items = new ArrayList<>(); public double total = 0.0; } cart.items.add(item); cart.total += item.price();
After state is private; the invariant lives inside the unit.
public final class ShoppingCart { private final List<Item> items = new ArrayList<>(); private double total = 0.0; public void add(Item item) { this.items.add(item); this.total += item.price(); } public double getTotal() { return this.total; } }
Before callers maintain the invariant by hand. One forgets and total drifts.
class ShoppingCart { public array $items = []; public float $total = 0.0; } $cart->items[] = $item; $cart->total += $item->price;
After state is private; the invariant lives inside the unit.
final class ShoppingCart { private array $items = []; private float $total = 0.0; public function add(Item $item): void { $this->items[] = $item; $this->total += $item->price; } public function getTotal(): float { return $this->total; } }
Enforcement
Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| @typescript-eslint/explicit-member-accessibility | typescript-eslint | class members without an explicit access modifier: public-by-default is a leak by accident. |
| @typescript-eslint/no-explicit-any | typescript-eslint | any-typed return values and parameters that erase the contract the interface promised. |
| @typescript-eslint/prefer-readonly | typescript-eslint | private fields never reassigned: should be readonly, signalling immutability after construction. |
| @typescript-eslint/no-non-null-assertion | typescript-eslint | the ! operator: a lie to the compiler about your invariant. Prove it with a guard. |
| no-unused-private-class-members | ESLint core | private members never read: dead encapsulated state. |
eslint.config.mjsconfiguration snippet
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
export default defineConfig({
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.base],
languageOptions: {
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
},
rules: {
// Encapsulation hygiene: no leaking implementation as 'any'.
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
// Class-level encapsulation: fields must declare visibility.
'@typescript-eslint/explicit-member-accessibility': [
'error',
{ accessibility: 'explicit' },
],
'@typescript-eslint/parameter-properties': ['error', { prefer: 'parameter-property' }],
'no-unused-private-class-members': 'error',
// No mutable public state.
'@typescript-eslint/prefer-readonly': 'error',
'@typescript-eslint/prefer-readonly-parameter-types': 'off', // expensive; opt in per repo
}
});Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| @typescript-eslint/explicit-member-accessibility | typescript-eslint | class members without an explicit access modifier: public-by-default is a leak by accident. |
| @typescript-eslint/no-explicit-any | typescript-eslint | any-typed return values and parameters that erase the contract the interface promised. |
| @typescript-eslint/prefer-readonly | typescript-eslint | private fields never reassigned: should be readonly, signalling immutability after construction. |
| @typescript-eslint/no-non-null-assertion | typescript-eslint | the ! operator: a lie to the compiler about your invariant. Prove it with a guard. |
| no-unused-private-class-members | ESLint core | private members never read: dead encapsulated state. |
eslint.config.mjsconfiguration snippet
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
export default defineConfig({
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.base],
languageOptions: {
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
},
rules: {
// Encapsulation hygiene: no leaking implementation as 'any'.
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
// Class-level encapsulation: fields must declare visibility.
'@typescript-eslint/explicit-member-accessibility': [
'error',
{ accessibility: 'explicit' },
],
'@typescript-eslint/parameter-properties': ['error', { prefer: 'parameter-property' }],
'no-unused-private-class-members': 'error',
// No mutable public state.
'@typescript-eslint/prefer-readonly': 'error',
'@typescript-eslint/prefer-readonly-parameter-types': 'off', // expensive; opt in per repo
}
});Apply these rules in eslint.config.mjs. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| no-unused-private-class-members | ESLint core | private fields never read: likely a leak through another path. |
| class-methods-use-this | ESLint core | instance methods that ignore this: usually want to be static, or want to live elsewhere entirely. |
eslint.config.mjsconfiguration snippet
import js from '@eslint/js';
export default [
js.configs.recommended,
{
files: ['**/*.{js,mjs,cjs}'],
rules: {
'no-unused-private-class-members': 'error',
'class-methods-use-this': 'warn',
},
},
];Apply these rules in pyproject.toml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| PLR0904 (too-many-public-methods) | Ruff | wide public surfaces: usually a sign the class has stopped being one thing. |
| B009 (get-attr-with-constant) / B010 (set-attr-with-constant) | Ruff | getattr/setattr with literal names: bypassing the public interface. |
| protected-access (W0212) | pylint | external code touching _protected attributes: a violation of the convention contract. |
pyproject.tomlconfiguration snippet
[tool.ruff.lint]
select = [
"PLR", # pylint refactor: limits class size and method count
"B", # flake8-bugbear: catches B009/B010 (getattr/setattr abuse)
"SIM", # flake8-simplify
"ARG", # unused arguments: leaky parameter surface
]
[tool.ruff.lint.pylint]
max-public-methods = 7 # Caps the public interface of a class.
# Ruff has no setting that caps the number of class attributes.
# pylint (when invoked alongside Ruff) for protected-access:
# pylint --disable=all --enable=protected-access src/Apply these rules in checkstyle.xml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| VisibilityModifier | Checkstyle | non-final public/protected fields: leaks of mutable state. |
| S1104 (Fields should not be public) | SonarQube Java | public fields outside of explicit value-object patterns. Pair with record for the legitimate cases. |
| FinalClass | Checkstyle | classes with private constructors and no inheritor: should be final to close the substitution surface. |
| MutableException | Checkstyle | exceptions with mutable state: exception classes must be value-like. |
checkstyle.xmlconfiguration snippet
<!-- checkstyle.xml: encapsulation rules -->
<module name="Checker">
<module name="TreeWalker">
<!-- No public mutable fields. Use accessors. -->
<module name="VisibilityModifier">
<property name="protectedAllowed" value="false"/>
<property name="packageAllowed" value="false"/>
<property name="allowPublicFinalFields" value="true"/>
</module>
<!-- Final classes when not designed for inheritance. -->
<module name="FinalClass"/>
<!-- Hide constructors of utility classes. -->
<module name="HideUtilityClassConstructor"/>
<module name="OneTopLevelClass"/>
<module name="MutableException"/>
</module>
</module>
<!-- SonarQube rules to add: S1104 (fields should not be public), S1444 (public static
fields should be final), S2386 (static arrays should not be exposed). -->Apply these rules in phpcs.xml. The full enforcement across every tenet lives on the implementation page.
| Rule | Tool | Catches |
|---|---|---|
| Squiz.Scope.MemberVarScope | PHP_CodeSniffer | class properties without explicit visibility: public by default is a leak. |
| Squiz.Scope.MethodScope | PHP_CodeSniffer | methods without explicit visibility: same problem one level up. |
| TooManyMethods / TooManyPublicMethods | PHPMD | wide public surfaces: usually a hidden SRP violation behind the encapsulation. |
phpcs.xmlconfiguration snippet
<?xml version="1.0"?>
<ruleset name="prickles-encapsulation">
<rule ref="PSR12"/>
<!-- All members and methods declare visibility. -->
<rule ref="Squiz.Scope.MemberVarScope"/>
<rule ref="Squiz.Scope.MethodScope"/>
<!-- Unused parameters: interface surface the body never reads. -->
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/>
<!-- PHPMD complementary rules:
- ExcessivePublicCount / TooManyPublicMethods (cap public surface)
- UnusedPrivateField -->
</ruleset>AI rules
.cursor/rules/f6-encapsulation.mdc--- alwaysApply: true --- ## Prickles F6: Encapsulation Hide the inside of your code. Callers should only call methods: never read or change fields directly. The method names are the contract. The body of the code is private and free to change. If state has to change, give callers a method that does the change safely. The method enforces the rules. The field stays private. Don't expose a field for the caller to update by hand. Always mark every field and method as `public` or `private` on purpose. Never rely on the language default. If it's only used inside the unit, mark it `private`. F6 is not the same as F1. F1 says each unit does one thing. F6 says each unit keeps its insides private. A focused class with public mutable fields passes F1 and fails F6: they catch different mistakes. Why it matters: hidden internals make change cheap. You can rewrite the body without breaking any caller, because no caller depends on the body. Leaked internals fuse the unit to every callsite that touched them, and every change becomes a graph search.
Repo layout, CI, and ESLint wiring for these paths live on /implementation, not repeated on every tenet.
Counter-argument
The steelman has two heads. The first is Ousterhout's: shallow modules with ceremonial encapsulation (getter for every field, public method for every internal operation) are no improvement on direct field access. They double the surface area while hiding nothing. The second is the value-object case: some objects (DTOs, plain records, schemas) are supposed to expose their fields. Forcing accessors on them produces ceremony and noise. F6 naively applied produces JavaBean clutter or anaemic OO designs where every class is a shell of getters.
Counter-argument retort
The first head is right and is the operational refinement F6 needs. Encapsulation is not a count of accessors; it is the depth of behaviour behind an interface. A module with twenty getters and no behaviour has not encapsulated anything. It has built a protocol-buffer in OO clothes. The principle Ousterhout names, deep modules, is the goal F6 is in service of. Treat narrow interface, substantial body as the criterion, not private keyword on every field.
The second head is also true and is absorbed by F6, not refuted by it. Value objects, DTOs, schemas, and language-level record / data class constructs are precisely the cases where the public state is the contract. Use them. The modern languages have first-class support. F6 says public mutable state is a defect; immutable value-objects are the case the rule has the language-level escape hatch for.
Default stance for behaviour-bearing units: visibility declared, public state private, Tell-Don't-Ask, narrow interface, substantial body. Default stance for value-bearing units: readonly, immutable, all-public-by-design. Anything else is an exception that gets defended in the PR description.
Notes
- [1]David Parnas: On the Criteria to be Used in Decomposing Systems into Modules: CMU TR CMU-CS-71-101 (August 1971); Communications of the ACM 15(12), 1053-1058 (December 1972). The foundational paper. The KWIC index example begins on p. 3 of the technical report. The information-hiding criterion is in the section titled 'The Criteria' (p. 17).
- [2]Barbara Liskov: Data Abstraction and Hierarchy: OOPSLA '87 keynote, addendum published in ACM SIGPLAN Notices 23(5), 17-34, May 1988. Formalised as the Liskov Substitution Principle by Liskov & Wing (1994).
- [3]Bertrand Meyer: Object-Oriented Software Construction (2nd ed., Prentice-Hall 1997). Design by Contract, preconditions, postconditions, class invariants, as the executable form of the encapsulated interface. Eiffel was the first language with first-class contract syntax.
- [4]Gamma, Helm, Johnson, Vlissides: Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994). 'Encapsulate what varies' is the through-line. The catalogue is twenty-three answers to where to draw the encapsulation boundary.
- [5]Joshua Bloch: Effective Java, 3rd ed. (Addison-Wesley, 2018). Item 15 'Minimize the accessibility of classes and members' is the modern Java textbook formulation; Item 17 'Minimize mutability' is the value-object pair.