code-patterns
Common code patterns and best practices reference for quick lookup
Best use case
code-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Common code patterns and best practices reference for quick lookup
Common code patterns and best practices reference for quick lookup
Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.
Practical example
Example input
Use the "code-patterns" skill to help with this workflow task. Context: Common code patterns and best practices reference for quick lookup
Example output
A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.
When to use this skill
- Use this skill when you want a reusable workflow rather than writing the same prompt again and again.
When not to use this skill
- Do not use this when you only need a one-off answer and do not need a reusable workflow.
- Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/code-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How code-patterns Compares
| Feature / Agent | code-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Common code patterns and best practices reference for quick lookup
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Code Patterns Reference
Quick reference for common patterns. Use these as starting points, not rigid templates.
## Creational Patterns
### Factory
```typescript
// When: Creating objects without specifying exact class
interface Product { use(): void }
class ConcreteProductA implements Product {
use() { console.log('Using A') }
}
class ProductFactory {
static create(type: string): Product {
const products = { a: ConcreteProductA };
return new products[type]();
}
}
```
### Builder
```typescript
// When: Complex object construction with many optional params
class QueryBuilder {
private query = { select: '*', from: '', where: [] };
select(fields: string) { this.query.select = fields; return this; }
from(table: string) { this.query.from = table; return this; }
where(condition: string) { this.query.where.push(condition); return this; }
build() { return this.query; }
}
// Usage
const query = new QueryBuilder()
.select('name, email')
.from('users')
.where('active = true')
.build();
```
### Singleton
```typescript
// When: Exactly one instance needed (use sparingly!)
class Database {
private static instance: Database;
private constructor() {}
static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
```
## Structural Patterns
### Adapter
```typescript
// When: Making incompatible interfaces work together
interface ModernLogger { log(msg: string): void }
class LegacyLogger {
writeLog(message: string, level: number) { /* ... */ }
}
class LoggerAdapter implements ModernLogger {
constructor(private legacy: LegacyLogger) {}
log(msg: string) { this.legacy.writeLog(msg, 1); }
}
```
### Decorator
```typescript
// When: Adding behavior without modifying original
interface Coffee { cost(): number; description(): string }
class SimpleCoffee implements Coffee {
cost() { return 5; }
description() { return 'Coffee'; }
}
class MilkDecorator implements Coffee {
constructor(private coffee: Coffee) {}
cost() { return this.coffee.cost() + 2; }
description() { return this.coffee.description() + ' + Milk'; }
}
```
## Behavioral Patterns
### Strategy
```typescript
// When: Algorithm should be selectable at runtime
interface PaymentStrategy {
pay(amount: number): void;
}
class CreditCardPayment implements PaymentStrategy {
pay(amount: number) { console.log(`Paid ${amount} via credit card`); }
}
class PayPalPayment implements PaymentStrategy {
pay(amount: number) { console.log(`Paid ${amount} via PayPal`); }
}
class Checkout {
constructor(private strategy: PaymentStrategy) {}
process(amount: number) { this.strategy.pay(amount); }
}
```
### Observer
```typescript
// When: Objects need to be notified of state changes
type Listener<T> = (data: T) => void;
class EventEmitter<T> {
private listeners: Listener<T>[] = [];
subscribe(listener: Listener<T>) {
this.listeners.push(listener);
return () => this.listeners = this.listeners.filter(l => l !== listener);
}
emit(data: T) {
this.listeners.forEach(l => l(data));
}
}
```
## Error Handling Patterns
### Result Type
```typescript
// When: Errors are expected, not exceptional
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return { ok: false, error: 'Division by zero' };
return { ok: true, value: a / b };
}
const result = divide(10, 2);
if (result.ok) {
console.log(result.value); // 5
} else {
console.error(result.error);
}
```
### Retry with Backoff
```typescript
// When: Transient failures are expected
async function retry<T>(
fn: () => Promise<T>,
attempts = 3,
delay = 1000
): Promise<T> {
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (e) {
if (i === attempts - 1) throw e;
await new Promise(r => setTimeout(r, delay * Math.pow(2, i)));
}
}
throw new Error('Unreachable');
}
```
## Async Patterns
### Promise Queue
```typescript
// When: Limiting concurrent async operations
class PromiseQueue {
private queue: (() => Promise<any>)[] = [];
private running = 0;
constructor(private concurrency: number) {}
add<T>(fn: () => Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
this.queue.push(async () => {
try { resolve(await fn()); }
catch (e) { reject(e); }
});
this.process();
});
}
private async process() {
if (this.running >= this.concurrency || !this.queue.length) return;
this.running++;
await this.queue.shift()!();
this.running--;
this.process();
}
}
```
### Debounce
```typescript
// When: Limiting rapid-fire function calls
function debounce<T extends (...args: any[]) => any>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
```
## Data Patterns
### Repository
```typescript
// When: Abstracting data access
interface Repository<T> {
findById(id: string): Promise<T | null>;
findAll(): Promise<T[]>;
save(entity: T): Promise<T>;
delete(id: string): Promise<void>;
}
class UserRepository implements Repository<User> {
constructor(private db: Database) {}
async findById(id: string) {
return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
}
// ... other methods
}
```
### Unit of Work
```typescript
// When: Coordinating writes across multiple repositories
class UnitOfWork {
private operations: (() => Promise<void>)[] = [];
register(operation: () => Promise<void>) {
this.operations.push(operation);
}
async commit() {
await this.db.beginTransaction();
try {
for (const op of this.operations) await op();
await this.db.commit();
} catch (e) {
await this.db.rollback();
throw e;
}
}
}
```
## When to Use Each
| Problem | Pattern |
|---------|---------|
| Complex object creation | Builder |
| Multiple similar objects | Factory |
| Global state (careful!) | Singleton |
| Incompatible interfaces | Adapter |
| Adding features dynamically | Decorator |
| Swappable algorithms | Strategy |
| Event-based communication | Observer |
| Expected failures | Result Type |
| Transient failures | Retry |
| Rate limiting | Debounce/Throttle |
| Data access abstraction | Repository |
| Transactional consistency | Unit of Work |Related Skills
python-design-patterns
Python design patterns including KISS, Separation of Concerns, Single Responsibility, and composition over inheritance. Use when making architecture decisions, refactoring code structure, or evaluating when abstractions are appropriate.
design-system-patterns
Build scalable design systems with design tokens, theming infrastructure, and component architecture patterns. Use when creating design tokens, implementing theme switching, building component libraries, or establishing design system foundations.
vercel-composition-patterns
React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture.
ui-component-patterns
Build reusable, maintainable UI components following modern design patterns. Use when creating component libraries, implementing design systems, or building scalable frontend architectures. Handles React patterns, composition, prop design, TypeScript, and component best practices.
zapier-make-patterns
No-code automation democratizes workflow building. Zapier and Make (formerly Integromat) let non-developers automate business processes without writing code. But no-code doesn't mean no-complexity - these platforms have their own patterns, pitfalls, and breaking points. This skill covers when to use which platform, how to build reliable automations, and when to graduate to code-based solutions. Key insight: Zapier optimizes for simplicity and integrations (7000+ apps), Make optimizes for power
workflow-patterns
Use this skill when implementing tasks according to Conductor's TDD workflow, handling phase checkpoints, managing git commits for tasks, or understanding the verification protocol.
workflow-orchestration-patterns
Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.
wcag-audit-patterns
Conduct WCAG 2.2 accessibility audits with automated testing, manual verification, and remediation guidance. Use when auditing websites for accessibility, fixing WCAG violations, or implementing accessible design patterns.
unity-ecs-patterns
Master Unity ECS (Entity Component System) with DOTS, Jobs, and Burst for high-performance game development. Use when building data-oriented games, optimizing performance, or working with large entity counts.
stride-analysis-patterns
Apply STRIDE methodology to systematically identify threats. Use when analyzing system security, conducting threat modeling sessions, or creating security documentation.
sql-optimization-patterns
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
rust-async-patterns
Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.