- Home
- Skills
- Yanko Belov
- Code Craft
- Encapsulation
encapsulation_skill
- TypeScript
6
GitHub Stars
1
Bundled Files
2 months ago
Catalog Refreshed
4 months ago
First Indexed
Readme & install
Copy the install command, review bundled files from the catalogue, and read any extended description pulled from the listing source.
Installation
Preview and clipboard use veilstrat where the catalogue uses aiagentskills.
npx veilstrat add skill yanko-belov/code-craft --skill encapsulation- SKILL.md5.9 KB
Overview
This skill enforces encapsulation when designing TypeScript classes. It helps you hide internal state, expose behavior through methods, and prevent external code from breaking invariants. Use it to replace public mutable fields with private state, validated methods, and safe read-only views.
How this skill works
The skill inspects class designs and detects patterns that expose internal state: public mutable fields, methods that return live references to internal arrays/objects, and missing validation on state changes. It recommends converting public fields to private properties, adding getters/setters with validation, returning copies or ReadonlyArray, and using readonly for immutable configuration.
When to use it
- Designing classes that hold state
- Tempted to make fields public for convenience
- External code directly mutates object internals
- You need to protect invariants and audit trails
- When arrays/objects are returned by reference
Best practices
- Make mutable fields private and expose behavior via methods
- Validate every state change in setters or methods
- Return copies or ReadonlyArray instead of live references
- Use readonly for configuration that must not change
- Prefer clear method names (deposit/withdraw) over direct assignments
Example use cases
- Bank account class: private balance, deposit/withdraw methods with validation and transaction logging
- Order management: return a copy or ReadonlyArray of items to prevent caller mutation
- User credentials: private password field with setPassword and checkPassword methods
- Configuration objects: readonly fields set at construction to prevent runtime mutation
- Migration of legacy code that uses public fields to an encapsulated API
FAQ
Public fields are simpler to write but allow callers to violate invariants, break audits, and tightly couple consumers to internal representation. Encapsulation prevents those issues.
How do I expose read-only data without copying large arrays?
Return a ReadonlyArray<T> or provide iterator/accessor methods instead of returning the internal array directly. If performance is critical, document and control access carefully or provide defensive methods rather than raw references.