Skip to main content
ClaudeWave
EN, English
Skill286 repo starsupdated 7mo ago

universal-patterns

The universal-patterns Claude Code skill provides language-agnostic architectural and organizational principles including layered architecture, clean architecture, component-based design, and coding practices like single responsibility and dependency injection. Use this skill when designing system structure, organizing code across any technology stack, establishing separation of concerns, or implementing standard development patterns that apply regardless of programming language or framework.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/MadAppGang/claude-code /tmp/universal-patterns && cp -r /tmp/universal-patterns/plugins/dev/skills/core/universal-patterns ~/.claude/skills/universal-patterns
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# 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 duplica
adr-documentationSkill

Architecture Decision Records (ADR) documentation practice. Use when documenting architectural decisions, recording technical trade-offs, creating decision logs, or establishing architectural patterns. Trigger keywords - "ADR", "architecture decision", "decision record", "trade-offs", "architectural decision", "decision log".

agent-coordination-disciplineSkill

Use when deciding whether to launch an agent, selecting which agent to use, or coordinating multiple agents. Covers delegation criteria, external-model patterns, task isolation, and agent selection strategies.

api-designSkill

Use when designing REST or GraphQL APIs, defining endpoints, implementing pagination/filtering, handling API versioning, or establishing API documentation with OpenAPI/Swagger.

api-integrationSkill

Use when integrating Apidog + OpenAPI specifications with your React app. Covers MCP server setup, type generation, and query layer integration. Use when setting up API clients, generating types from OpenAPI, or integrating with Apidog MCP.

api-spec-analyzerSkill

Analyzes API documentation from OpenAPI specs to provide TypeScript interfaces, request/response formats, and implementation guidance. Use when implementing API integrations, debugging API errors (400, 401, 404), replacing mock APIs, verifying data types, or when user mentions endpoints, API calls, or backend integration.

architect-detectiveSkill

Use when analyzing architecture and system design. Find design patterns, map layers, identify core abstractions via PageRank. Uses claudemem AST structural analysis for efficient architecture investigation.

auditSkill

On-demand security and code quality audit. Use when checking for vulnerabilities, security issues, code smells, or compliance problems. Trigger keywords - "audit", "security check", "vulnerability scan", "code quality", "compliance", "security audit".

auth-patternsSkill

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