Class Generation Patterns
Generate a class from responsibilities + invariants; prefer composition over inheritance.
Why
GitHub's 2024 Octoverse reported a 59% surge in contributions to generative AI projects and a 98% increase in AI projects overall on the platform. Classes generated without stated invariants tend to leak state and mix concerns.
Stating responsibilities and invariants up front yields a cohesive class with a clear public API and encapsulated state.
When
Use for stateful modules (repositories, services, state machines). Skip for pure functions.
How
Example
Common Problems
- ⚠Generated code fails to compile: "SyntaxError: Unexpected token" → ask the model to output a complete file with correct imports; verify with `npx tsc --noEmit`.
- ⚠Error: Hallucinated API: model calls a function that doesn't exist → cross-check against the actual library docs and pin the version in package.json.
- ⚠Error: Cannot find module 'xxx' → `npm install xxx`; generated code often imports packages not yet in the project.
Best Practices
- ✓State responsibilities and invariants before the body.
- ✓Keep state private; expose only the public API.
- ✓Measure the outcome with a concrete metric (time saved, defect rate, test coverage) so the practice can be justified and improved.
FAQ
What is Class Generation Patterns?
Generate a class from responsibilities + invariants; prefer composition over inheritance. It helps developers quickly grasp the core value and use cases of Class Generation Patterns.
How do I get started with Class Generation Patterns?
To get started with Class Generation Patterns, focus on these points first: List responsibilities (single responsibility per class).
What are common mistakes with Class Generation Patterns?
Common mistakes when using Class Generation Patterns include: Generated code fails to compile: "SyntaxError: Unexpected token" → ask the model to output a complete file with correct imports; verify with `npx tsc --noEmit`.; Error: Hallucinated API: model calls a function that doesn't exist → cross-check against the actual library docs and pin the version in package.json.; Error: Cannot find module 'xxx' → `npm install xxx`; generated code often imports packages not yet in the project..
What are the best practices for Class Generation Patterns?
Best practices for Class Generation Patterns include: State responsibilities and invariants before the body.; Keep state private; expose only the public API.; Measure the outcome with a concrete metric (time saved, defect rate, test coverage) so the practice can be justified and improved..
How do I learn more about Class Generation Patterns?
Start with the official docs, then search real-world examples on GitHub. Validate patterns in a small scratch repo before applying them to production code.