design-patterns
Skill547 starsChanged 3 months agoMITView on GitHub
Agents should invoke this skill when choosing patterns, designing traits/interfaces/components, deciding abstraction boundaries, evaluating dependency injection/callbacks, or comparing implementation approaches in Rust, TypeScript/React, or Django/Python.
We split this skill into the rules it gives an agent
3 rules. 0 are common, 3 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 31 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 38
When to use: When two values have the same underlying type but different meanings.
- Distinctive: line 216
Rule of thumb: Use signals for truly cross-cutting concerns (audit logging, cache invalidation).
- Distinctive: line 236
When asked "which pattern should I use?":
“Common” is measured: kept by at least 6 in 10 of the 31 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Design Patterns
Pattern recommendations tailored to common tech stacks. Every pattern recommendation includes when to use it, when to avoid it, and the trade-offs.
Quick Start
Choose a Pattern
- Identify the problem: What design challenge are you solving?
- Consider the context: What language? What scale? How often will this change?
- Evaluate options: 2-3 candidate patterns with trade-offs
- Recommend: The best fit for this specific context (not the "best pattern in general")
The golden rule: Patterns are tools, not goals. Use the simplest pattern that solves the problem. If no pattern fits, a plain function or struct is fine.
Rust Patterns
Newtype Pattern
Wrap a primitive to add type safety and domain meaning.
struct UserId(u64);
struct OrderId(u64);
// Now the compiler prevents mixing up UserId and OrderId
fn get_order(user: UserId, order: OrderId) -> Order { ... }When to use: When two values have the same underlying type but different meanings. When to skip: One-off uses where a type alias suffices.
Builder Pattern
Construct complex objects step by step.
let config = ServerConfig::builder()
.host("localhost")
.port(8080)
.max_connections(100)
.build()?;When to use: Structs with many optional fields, complex construction logic.
When to skip: Structs with 1-3 required fields — just use new().
Typestate Pattern
Encode state transitions in the type system so invalid states are unrepresentable.
struct Connection<S: State> { /* ... */ state: PhantomData<S> }
struct Disconnected;
struct Connected;
struct Authenticated;
impl Connection<Disconnected> {
fn connect(self) -> Result<Connection<Connected>> { ... }
}
impl Connection<Connected> {
fn authenticate(self, creds: &Credentials) -> Result<Connection<Authenticated>> { ... }
}
impl Connection<Authenticated> {
fn query(&self, sql: &str) -> Result<Rows> { ... }
}
// Can't call query() on a Disconnected connection — compile errorWhen to use: Protocols with clear state transitions (connections, workflows, parsing stages). When to skip: Simple on/off states — a boolean or enum is clearer.
Trait Objects vs Generics
| Approach | Dispatch | Binary Size | Flexibility |
impl Trait (generics) | Static (monomorphized) | Larger (one copy per type) | Known at compile time |
dyn Trait (trait objects) | Dynamic (vtable) | Smaller (one copy) | Extensible at runtime |
Use generics when: Performance matters, types are known at compile time, you want zero-cost abstraction. Use trait objects when: You need heterogeneous collections, plugin systems, or the set of types is open-ended.
Error Handling Patterns
| Pattern | When | Crate |
thiserror | Library errors — structured, specific variants | thiserror |
anyhow | Application errors — context-rich, propagate quickly | anyhow |
| Custom enum | When you need exhaustive matching by callers | std only |
Rule of thumb: Libraries use thiserror (callers need to match). Applications use anyhow (callers need context).
TypeScript / React Patterns
Compound Components
Components that work together implicitly via shared context.
<Select>
<Select.Trigger>Choose a fruit</Select.Trigger>
<Select.Options>
<Select.Option value="apple">Apple</Select.Option>
<Select.Option value="banana">Banana</Select.Option>
</Select.Options>
</Select>When to use: Complex UI components with multiple related parts (menus, accordions, tabs). When to skip: Simple components with 1-2 elements.
Custom Hook Composition
Extract and compose behavior into reusable hooks.
function useDebounce<T>(value: T, delay: number): T { ... }
function usePagination(items: Item[], pageSize: number) { ... }
function useLocalStorage<T>(key: string, initial: T) { ... }When to use: Shared stateful logic across components, complex state management within a component. When to skip: One-off logic that doesn't repeat.
Discriminated Unions
Type-safe state modeling using TypeScript's union types.
type AsyncState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
// Exhaustive switch — TypeScript ensures all cases handled
function render(state: AsyncState<User>) {
switch (state.status) {
case "idle": return <Placeholder />;
case "loading": return <Spinner />;
case "success": return <UserCard user={state.data} />;
case "error": return <ErrorBanner error={state.error} />;
}
}When to use: State machines, API response states, form states, anything with distinct modes. When to skip: Boolean flags are fine for simple on/off states.
State Management Decision Tree
- UI-local state? ->
useState/useReducer - Shared between siblings? -> Lift state to common parent
- Shared across distant components? -> React Context
- Complex state logic? ->
useReducer+ Context - Server state (API data)? -> TanStack Query / SWR
- Global app state? -> Zustand / Jotai (prefer over Redux for new projects)
Django / Python Patterns
Service Layer
Separate business logic from views and models.
# services/order_service.py
class OrderService:
@staticmethod
def create_order(user: User, items: list[CartItem]) -> Order:
"""Business logic lives here, not in the view."""
order = Order.objects.create(user=user, total=calculate_total(items))
OrderItem.objects.bulk_create([...])
send_confirmation_email(user, order)
return orderWhen to use: Business logic that involves multiple models, external calls, or complex validation. When to skip: Simple CRUD with no business rules beyond Django's built-in validation.
Repository Pattern (QuerySet Abstraction)
Custom managers and querysets to encapsulate query logic.
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status="published")
class Article(models.Model):
objects = models.Manager() # Default
published = PublishedManager() # Article.published.all()When to use: Complex or reusable query logic, domain-specific filtering. When to skip: One-off queries or simple filters.
Signals vs Explicit Calls
| Approach | Pros | Cons |
| Django signals | Decoupled, works across apps | Hidden control flow, hard to debug, ordering issues |
| Explicit calls | Visible, debuggable, testable | Coupling between modules |
Rule of thumb: Use signals for truly cross-cutting concerns (audit logging, cache invalidation). Use explicit calls for business-critical logic where you need to understand and test the flow.
Anti-Patterns (All Stacks)
| Anti-Pattern | Problem | Fix |
| Premature abstraction | Abstracting before seeing the pattern repeat | Wait for 3 instances before extracting |
| Inheritance over composition | Deep inheritance hierarchies, fragile base class | Prefer composition (traits, hooks, mixins) |
| God object | One class/module that does everything | Split by responsibility (SRP) |
| Shotgun surgery | One change requires editing many files | Group related code together |
| Feature envy | A function uses another class's data more than its own | Move the function to the class it envies |
| Speculative generality | Building for use cases that may never come | YAGNI — build for now, refactor when needed |
| Golden hammer | Using the same pattern/tool for everything | Choose the right tool for the job |
Pattern Selection Guide
When asked "which pattern should I use?":
- Describe the problem (not the pattern you think fits)
- Identify constraints (performance, extensibility, team size, timeline)
- Present 2-3 options with trade-offs
- Recommend one with clear justification
- Note when to revisit — "If X changes, reconsider Y"
Integration
Cross-reference this pack's code-architect skill for structural/architecture assessment and code-quality for the complexity thresholds that motivate refactoring toward a pattern.
Other versions32 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 32
- rtk-ai/rtk★ 85ksame name
- piomin/claude-ai-spring-boot★ 1.4ksame name
- decebals/claude-code-java★ 763same name
- FlorianBruniaux/ccboard★ 94same name
- nimadorostkar/Claude-Skills-collection★ 33same name
- DIL8654/claude-code-dotnet-template★ 8same name
- tstapler/dotfiles★ 8same name
- cookieMonsterDev/agents-skills★ 7same name
- piomin/claude-ai-quarkus★ 7same name
- kayaman/skills★ 3same name
22 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use logging-patterns, tdd-rust and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
DIL8654Skilllogging-patterns
Keep logs structured, correlated, low-noise, and safe for production support. Use when adding operational logging, reviewing observability, or improving diagnostics in .NET services.
Also in 6 projects that use this
FlorianBruniauxSkilltdd-rust
Also in 3 projects that use this
mstuder-slalomSkilljpa-patterns
JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.
Also in 5 projects that use this
ufodev-ioSkillsecurity-guardian
Comprehensive security layer for all interactions with Claude: audits code, dependencies, commands, configs, and AI-generated output for vulnerabilities. Protects against prompt injection, data leaks, unsafe advice, and social engineering. Works in Cursor, Claude Code, claude.ai, and API contexts. Use always as a background security protocol in any Claude-powered environment.
Also in 3 projects that use this
nek1987Skillsolid-principles
SOLID object-oriented design principles for maintainable code
Also in 4 projects that use this
tossSkillpr-triage
Classify and summarize a PR for efficient review
Also in 3 projects that use this
In this repository54 other files it gives its agents.
- agentic-actions-auditorSkill
- agents-md-improverSkill
- agents-md-reviseSkill
- ai-slopSkill
- code-architectSkill
- code-explorerSkill
- codeqlSkill
- code-qualitySkill
- code-reviewerSkill
- code-reviewSkill
- differential-reviewSkill
- feature-devSkill
- fp-checkSkill
- frontend-designSkill
- hf-cliSkill
- hf-cloud-aws-context-discoverySkill
- hf-cloud-python-env-setupSkill
- hf-cloud-sagemaker-deployment-plannerSkill
- hf-cloud-sagemaker-iam-preflightSkill
- hf-cloud-sagemaker-production-defaultsSkill
- hf-cloud-serving-image-selectionSkill
- hf-memSkill
- huggingface-bestSkill
- huggingface-community-evalsSkill
- huggingface-datasetsSkill
- huggingface-gradioSkill
- huggingface-llm-trainerSkill
- huggingface-local-modelsSkill
- huggingface-lora-space-builderSkill
- huggingface-paper-publisherSkill
- huggingface-papersSkill
- huggingface-spacesSkill
- huggingface-tool-builderSkill
- huggingface-trackioSkill
- huggingface-vision-trainerSkill
- huggingface-zerogpuSkill
- humanizerSkill
- insecure-defaultsSkill
- mcp-builderSkill
- paper-summarizerSkill
- sarif-parsingSkill
- security-reviewSkill
- security-threat-modelSkill
- semgrep-rule-creatorSkill
- semgrep-rule-variant-creatorSkill
- semgrepSkill
- sharp-edgesSkill
- skill-creatorSkill
- supply-chain-risk-auditorSkill
- train-sentence-transformersSkill
- transformers-jsSkill
- trl-trainingSkill
- variant-analysisSkill
- vuln-reportSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

