universal-patterns

Use when implementing language-agnostic patterns like layered architecture, dependency injection, error handling, or code organization principles across any technology stack.

248 stars

Best use case

universal-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when implementing language-agnostic patterns like layered architecture, dependency injection, error handling, or code organization principles across any technology stack.

Teams using universal-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/universal-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/MadAppGang/claude-code/main/plugins/dev/skills/core/universal-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/universal-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How universal-patterns Compares

Feature / Agentuniversal-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when implementing language-agnostic patterns like layered architecture, dependency injection, error handling, or code organization principles across any technology stack.

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

# Universal Development Patterns

## Overview

Language-agnostic development patterns and best practices applicable across all technology stacks.

## Architecture Patterns

### Layered Architecture

```
┌─────────────────────────────┐
│     Presentation Layer      │  UI, API handlers, CLI
├─────────────────────────────┤
│     Application Layer       │  Use cases, services
├─────────────────────────────┤
│       Domain Layer          │  Business logic, entities
├─────────────────────────────┤
│    Infrastructure Layer     │  DB, cache, external APIs
└─────────────────────────────┘
```

**When to Use**: Most applications benefit from clear separation of concerns.

### Clean Architecture

```
         ┌─────────────────┐
         │   Frameworks    │  (outermost)
         │   & Drivers     │
     ┌───┴─────────────────┴───┐
     │    Interface Adapters    │
     │   (Controllers, Gateways)│
 ┌───┴─────────────────────────┴───┐
 │        Application Business      │
 │           Rules (Use Cases)      │
 ┌─────────────────────────────────┐
 │    Enterprise Business Rules     │  (innermost)
 │         (Entities)               │
 └─────────────────────────────────┘
```

**Dependency Rule**: Dependencies point inward. Inner layers don't know about outer layers.

### Component-Based Architecture (Frontend)

```
src/
├── components/
│   ├── common/         # Shared UI components
│   ├── layout/         # Layout components
│   └── features/       # Feature-specific components
├── hooks/              # Custom hooks
├── stores/             # State management
├── services/           # API services
└── utils/              # Utilities
```

## Code Organization Principles

### Single Responsibility

Each module/function should do ONE thing well.

```
// BAD: Multiple responsibilities
function processUser(user) {
  validateUser(user);
  saveToDatabase(user);
  sendEmail(user);
  logAnalytics(user);
}

// GOOD: Single responsibility
function validateUser(user) { /* validation only */ }
function saveUser(user) { /* persistence only */ }
function notifyUser(user) { /* notification only */ }
```

### Dependency Injection

Inject dependencies rather than creating them internally.

```
// BAD: Hard dependency
class UserService {
  constructor() {
    this.db = new Database(); // Hard-coded
  }
}

// GOOD: Injected dependency
class UserService {
  constructor(db) {
    this.db = db; // Injected
  }
}
```

### Interface Segregation

Prefer many specific interfaces over one general interface.

```
// BAD: Fat interface
interface Worker {
  work();
  eat();
  sleep();
}

// GOOD: Segregated interfaces
interface Workable { work(); }
interface Eatable { eat(); }
interface Sleepable { sleep(); }
```

## Error Handling Patterns

### Fail Fast

Validate inputs early and fail immediately on invalid data.

```
function processOrder(order) {
  // Validate early
  if (!order) throw new Error('Order required');
  if (!order.items?.length) throw new Error('Order must have items');
  if (!order.customerId) throw new Error('Customer ID required');

  // Process only after validation passes
  return executeOrder(order);
}
```

### Error Boundaries

Contain errors at appropriate boundaries.

```
// API boundary - catch and format errors
async function apiHandler(req, res) {
  try {
    const result = await processRequest(req);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(error.statusCode || 500).json({
      success: false,
      error: error.message
    });
  }
}
```

### Result Types (Where Supported)

Use Result/Either types instead of exceptions for expected failures.

```typescript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

function parseConfig(input: string): Result<Config, ParseError> {
  try {
    return { ok: true, value: JSON.parse(input) };
  } catch (e) {
    return { ok: false, error: new ParseError(e.message) };
  }
}
```

## Data Flow Patterns

### Unidirectional Data Flow

Data flows in one direction through the application.

```
Action → Dispatcher → Store → View → Action
```

### Event-Driven Architecture

Decouple components through events.

```
// Publisher
eventBus.emit('user.created', { userId: '123' });

// Subscriber
eventBus.on('user.created', async (event) => {
  await sendWelcomeEmail(event.userId);
});
```

### Command Query Separation (CQS)

Separate commands (mutations) from queries (reads).

```
// Query - returns data, no side effects
function getUser(id) { return db.users.find(id); }

// Command - mutates data, returns void/status
function updateUser(id, data) { db.users.update(id, data); }
```

## Naming Conventions

### Functions

| Type | Convention | Examples |
|------|------------|----------|
| Actions | verb + noun | `createUser`, `deleteOrder`, `validateInput` |
| Queries | get/find/is/has + noun | `getUser`, `findOrders`, `isValid`, `hasPermission` |
| Handlers | handle + event | `handleClick`, `handleSubmit`, `handleError` |
| Callbacks | on + event | `onSuccess`, `onError`, `onChange` |

### Variables

| Type | Convention | Examples |
|------|------------|----------|
| Booleans | is/has/can/should | `isActive`, `hasAccess`, `canEdit`, `shouldRefresh` |
| Collections | plural | `users`, `orders`, `items` |
| Counts | count/num/total | `userCount`, `numItems`, `totalPrice` |

### Files

| Type | Convention | Examples |
|------|------------|----------|
| Components | PascalCase | `UserProfile.tsx`, `OrderList.vue` |
| Utilities | camelCase/kebab | `formatDate.ts`, `string-utils.ts` |
| Constants | SCREAMING_SNAKE | `API_ENDPOINTS.ts`, `ERROR_CODES.ts` |
| Tests | name.test/spec | `user.test.ts`, `order.spec.ts` |

## Code Quality Checklist

Before committing code, verify:

- [ ] Single responsibility - each function does one thing
- [ ] Clear naming - intent is obvious from names
- [ ] Error handling - failures are handled gracefully
- [ ] No magic numbers - constants are named and documented
- [ ] DRY - no unnecessary duplication (but don't over-abstract)
- [ ] Tests - critical paths are tested
- [ ] Documentation - complex logic is explained

## Anti-Patterns to Avoid

### God Objects
Objects that know too much or do too much. Split into focused components.

### Premature Optimization
Don't optimize before measuring. Write clear code first, optimize proven bottlenecks.

### Stringly Typed
Using strings where enums/types would be safer. Use type systems.

### Copy-Paste Programming
Duplicating code instead of abstracting. But: prefer duplication over wrong abstraction.

### Boolean Parameters
Functions with boolean flags that change behavior. Split into explicit functions.

```
// BAD
function process(data, isAdmin) { /* behaves differently based on flag */ }

// GOOD
function processUserData(data) { /* user logic */ }
function processAdminData(data) { /* admin logic */ }
```

## Performance Principles

1. **Measure First**: Profile before optimizing
2. **Lazy Loading**: Load resources only when needed
3. **Caching**: Cache expensive computations and API calls
4. **Pagination**: Don't load everything at once
5. **Batch Operations**: Combine multiple operations when possible
6. **Async/Parallel**: Use concurrency for independent operations

## Security Principles

1. **Input Validation**: Never trust user input
2. **Output Encoding**: Encode data for its context (HTML, SQL, etc.)
3. **Least Privilege**: Request minimum permissions needed
4. **Defense in Depth**: Multiple layers of security
5. **Fail Secure**: Default to denying access on errors
6. **Secrets Management**: Never hardcode secrets, use environment variables

---

*Universal patterns applicable to all technology stacks*

Related Skills

data-extraction-patterns

248
from MadAppGang/claude-code

Common patterns for extracting analytics data from GA4 and GSC with API handling

batching-patterns

248
from MadAppGang/claude-code

Batch all related operations into single messages for maximum parallelism and performance. Use when launching multiple agents, reading multiple files, running parallel searches, optimizing workflow speed, or avoiding sequential execution bottlenecks. Trigger keywords - "batching", "parallel", "single message", "golden rule", "concurrent", "performance", "sequential bottleneck", "speed optimization".

ab-testing-patterns

248
from MadAppGang/claude-code

A/B testing methodology for cold email optimization

react-patterns

248
from MadAppGang/claude-code

Use when implementing React 19 features, optimizing components, or choosing between Actions vs TanStack Query for mutations. Covers React Compiler optimization, Server Actions, Forms, and new hooks.

plugin-sdk-patterns

248
from MadAppGang/claude-code

Unified patterns and templates for creating consistent Claude Code plugins. Use when creating new plugins, designing plugin architecture, implementing builder patterns, or standardizing plugin structure. Trigger keywords - "plugin SDK", "plugin template", "plugin pattern", "builder pattern", "plugin structure", "new plugin", "plugin architecture".

database-patterns

248
from MadAppGang/claude-code

Use when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL databases.

auth-patterns

248
from MadAppGang/claude-code

Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.

patterns

248
from MadAppGang/claude-code

Common agent patterns and templates for Claude Code. Use when implementing agents to follow proven patterns for Tasks integration, quality checks, and external model invocation via claudish CLI.

test-skill

248
from MadAppGang/claude-code

A test skill for validation testing. Use when testing skill parsing and validation logic.

bad-skill

248
from MadAppGang/claude-code

This skill has invalid YAML in frontmatter

release

248
from MadAppGang/claude-code

Plugin release process for MAG Claude Plugins marketplace. Covers version bumping, marketplace.json updates, git tagging, and common mistakes. Use when releasing new plugin versions or troubleshooting update issues.

openrouter-trending-models

248
from MadAppGang/claude-code

Fetch trending programming models from OpenRouter rankings. Use when selecting models for multi-model review, updating model recommendations, or researching current AI coding trends. Provides model IDs, context windows, pricing, and usage statistics from the most recent week.