Analyze codebase for GoF design patterns - detection, suggestions, evaluation with stack-aware adaptations
Install with Tessl CLI
npx tessl i github:FlorianBruniaux/claude-code-ultimate-guide --skill design-patterns71
Quality
58%
Does it follow best practices?
Impact
100%
1.29xAverage score across 3 eval scenarios
Optimize this skill with Tessl
npx tessl skill review --optimize ./examples/skills/design-patterns/SKILL.mdPurpose: Detect, suggest, and evaluate Gang of Four (GoF) design patterns in TypeScript/JavaScript codebases with stack-aware adaptations.
Trigger: User requests pattern detection or analysis Output: JSON report of patterns found with confidence scores and stack context
Workflow:
1. Stack Detection (package.json, tsconfig.json, framework files)
2. Pattern Search (Glob for candidates → Grep for signatures → Read for validation)
3. Classification (native to stack vs custom implementations)
4. Confidence Scoring (0.0-1.0 based on detection rules)
5. JSON Report GenerationExample invocation:
/design-patterns detect src/
/design-patterns analyze --format=jsonTrigger: User requests pattern suggestions or refactoring advice Output: Markdown report with prioritized suggestions and stack-adapted examples
Workflow:
1. Code Smell Detection (switch statements, long parameter lists, global state, etc.)
2. Pattern Matching (map smell → applicable patterns)
3. Stack Adaptation (prefer native framework patterns over custom implementations)
4. Priority Ranking (impact × feasibility)
5. Markdown Report with Code ExamplesExample invocation:
/design-patterns suggest src/payment/
/design-patterns refactor --focus=creationalTrigger: User requests pattern quality assessment Output: JSON report with scores per evaluation criterion
Workflow:
1. Pattern Identification (which pattern is implemented)
2. Criteria Assessment (correctness, testability, SOLID compliance, documentation)
3. Issue Detection (common mistakes, anti-patterns)
4. Scoring (0-10 per criterion)
5. JSON Report with RecommendationsExample invocation:
/design-patterns evaluate src/services/singleton.ts
/design-patterns quality --pattern=observerSources (in priority order):
package.json → Check dependencies and devDependenciesangular.json, next.config.*, nest-cli.json, vite.config.*tsconfig.json → Check compilerOptions, paths, lib*.jsx, *.tsx, *.vue presenceDetection Rules (from signatures/stack-patterns.yaml):
react in deps + *.jsx/*.tsx files@angular/core + angular.json@nestjs/core + nest-cli.jsonvue v3+ + *.vue filesexpress in deps + app.use patternsrxjs in deps + Observable usageredux/zustand in deps + store patternsprisma/typeorm in deps + schema filesOutput:
{
"stack_detected": {
"primary": "react",
"version": "18.2.0",
"secondary": ["typescript", "zustand", "prisma"],
"detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
"confidence": 0.95
}
}Search Strategy:
Glob Phase: Find candidate files by naming convention
*Singleton*.ts, *Factory*.ts, *Strategy*.ts, *Observer*.ts, etc.*Manager*.ts, *Builder*.ts, *Adapter*.ts, *Proxy*.ts, etc.Grep Phase: Search for pattern signatures (from signatures/detection-rules.yaml)
private constructor, static getInstance(), subscribe(), createXxx(), etc.Read Phase: Validate pattern structure
Confidence Scoring:
Classification:
native: Pattern implemented using stack-native features (React Context, Angular Services, NestJS Guards, etc.)custom: Manual TypeScript implementationlibrary: Third-party library providing pattern (RxJS Subject, Redux Store, etc.)Target Smells (from signatures/code-smells.yaml):
Detection Heuristics:
switch (.*type), switch (.*kind), switch (.*mode)function \w+\([^)]{60,}\) (approximation for >4 params)window\., global\., process\.env\.\w+ (not in config files)if.*state.*===.*&&.*if.*state.*===forEach.*notify, map.*\.emit\(Adaptation Logic (from signatures/stack-patterns.yaml):
IF pattern_detected == "custom" AND stack_has_native_equivalent:
SUGGEST: "Use stack-native pattern instead"
PROVIDE: Side-by-side comparison (current vs recommended)
ELSE IF code_smell_detected AND pattern_missing:
IF stack_provides_pattern:
SUGGEST: Stack-native implementation with examples
ELSE:
SUGGEST: Custom TypeScript implementation with best practices
ELSE IF pattern_implemented_incorrectly:
PROVIDE: Refactoring steps to fix anti-patternsExample Adaptations:
| Pattern | Stack | Native Alternative | Recommendation |
|---|---|---|---|
| Singleton | React | Context API + Provider | Use createContext() instead of getInstance() |
| Observer | Angular | RxJS Subject/BehaviorSubject | Use built-in Observables, not custom implementation |
| Decorator | NestJS | @Injectable() decorators + Interceptors | Use framework interceptors |
| Strategy | Vue 3 | Composition API composables | Use ref() + composables instead of classes |
| Chain of Responsibility | Express | Middleware (app.use()) | Use Express middleware chain |
| Command | Redux | Action creators + reducers | Use Redux actions, not custom command objects |
Criteria (from checklists/pattern-evaluation.md):
Scoring Guidelines:
Issue Detection:
{
"metadata": {
"scan_date": "2026-01-21T10:30:00Z",
"scope": "src/",
"files_scanned": 147,
"execution_time_ms": 2341
},
"stack_detected": {
"primary": "react",
"version": "18.2.0",
"secondary": ["typescript", "zustand", "prisma"],
"detection_sources": ["package.json", "tsconfig.json", "37 *.tsx files"],
"confidence": 0.95
},
"patterns_found": {
"singleton": [
{
"file": "src/lib/api-client.ts",
"lines": "5-28",
"confidence": 0.85,
"type": "custom",
"signals": ["private constructor", "static getInstance", "private static instance"],
"note": "Consider using React Context instead for better testability"
}
],
"observer": [
{
"file": "src/hooks/useAuth.ts",
"lines": "12-45",
"confidence": 0.92,
"type": "native",
"implementation": "React useState + useEffect",
"note": "Correctly using React's built-in observer pattern"
}
],
"factory": [
{
"file": "src/services/notification-factory.ts",
"lines": "8-67",
"confidence": 0.78,
"type": "custom",
"signals": ["createNotification method", "type discrimination", "returns interface"]
}
]
},
"summary": {
"total_patterns": 7,
"native_to_stack": 4,
"custom_implementations": 3,
"by_category": {
"creational": 2,
"structural": 3,
"behavioral": 2
},
"by_confidence": {
"high": 5,
"medium": 2,
"low": 0
}
},
"recommendations": [
"Consider replacing custom Singleton (api-client.ts) with React Context for better DI",
"Review Factory pattern (notification-factory.ts) - could be simplified with strategy pattern"
]
}# Design Pattern Suggestions
**Scope**: `src/payment/`
**Stack**: React 18 + TypeScript + Stripe
**Date**: 2026-01-21
---
## High Priority
### 1. Strategy Pattern → `src/payment/processor.ts:45-89`
**Code Smell**: Switch statement on payment type (4 cases, 78 lines)
**Current Implementation** (lines 52-87):
```typescript
switch (paymentType) {
case 'credit':
// 20 lines of credit card logic
break;
case 'paypal':
// 15 lines of PayPal logic
break;
case 'crypto':
// 18 lines of crypto logic
break;
case 'bank':
// 12 lines of bank transfer logic
break;
}Recommended (React-adapted Strategy):
// Define strategy interface
interface PaymentStrategy {
process: (amount: number) => Promise<PaymentResult>;
}
// Custom hooks as strategies
const useCreditPayment = (): PaymentStrategy => ({
process: async (amount) => { /* credit logic */ }
});
const usePaypalPayment = (): PaymentStrategy => ({
process: async (amount) => { /* PayPal logic */ }
});
// Strategy selection hook
const usePaymentStrategy = (type: PaymentType): PaymentStrategy => {
const strategies = {
credit: useCreditPayment(),
paypal: usePaypalPayment(),
crypto: useCryptoPayment(),
bank: useBankPayment(),
};
return strategies[type];
};
// Usage in component
const PaymentForm = ({ type }: Props) => {
const strategy = usePaymentStrategy(type);
const handlePay = () => strategy.process(amount);
// ...
};Impact:
src/cart/CartManager.ts:23-156Code Smell: Manual notification logic scattered across 8 methods
Current: Manual loops calling update functions Recommended: Use Zustand store (already in dependencies)
// Instead of custom observer:
import create from 'zustand';
interface CartStore {
items: CartItem[];
addItem: (item: CartItem) => void;
removeItem: (id: string) => void;
// Zustand automatically notifies subscribers
}
export const useCartStore = create<CartStore>((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
removeItem: (id) => set((state) => ({ items: state.items.filter(i => i.id !== id) })),
}));
// Components auto-subscribe:
const CartDisplay = () => {
const items = useCartStore((state) => state.items);
// Re-renders automatically on cart changes
};Impact:
### Evaluation Mode (JSON)
```json
{
"file": "src/services/config-singleton.ts",
"pattern": "singleton",
"lines": "5-34",
"scores": {
"correctness": 8,
"testability": 4,
"single_responsibility": 9,
"open_closed": 7,
"documentation": 6,
"overall": 6.8
},
"details": {
"correctness": {
"score": 8,
"rationale": "Implements singleton structure correctly with private constructor and static getInstance",
"issues": ["Missing thread-safety consideration (not critical in JS single-threaded context)"]
},
"testability": {
"score": 4,
"rationale": "Hard to mock or reset instance in tests",
"issues": [
"No reset method for test isolation",
"Static instance makes dependency injection impossible",
"Tests must run in specific order or share state"
],
"suggestions": [
"Add resetInstance() method for tests (with appropriate guards)",
"Consider using dependency injection instead"
]
},
"single_responsibility": {
"score": 9,
"rationale": "Focuses solely on configuration management",
"issues": []
},
"open_closed": {
"score": 7,
"rationale": "Configuration can be extended but requires modification for new sources",
"suggestions": ["Consider strategy pattern for configuration sources"]
},
"documentation": {
"score": 6,
"rationale": "Has JSDoc but missing rationale for singleton choice",
"suggestions": ["Document why singleton is chosen over DI", "Add usage examples"]
}
},
"recommendations": [
{
"priority": "high",
"suggestion": "Add test-friendly reset mechanism or refactor to use DI",
"rationale": "Current implementation makes testing difficult"
},
{
"priority": "medium",
"suggestion": "Document singleton rationale in JSDoc",
"rationale": "Team members should understand why global state is necessary here"
}
]
}.ts, .tsx).js, .jsx)--scope to limit scan to specific directories# Detect all patterns in src/
/design-patterns detect src/
# Detect only creational patterns
/design-patterns detect src/ --category=creational
# Focus on specific pattern
/design-patterns detect src/ --pattern=singleton# Get suggestions for payment module
/design-patterns suggest src/payment/
# Focus on specific smell
/design-patterns suggest src/ --smell=switch-on-type
# High priority only
/design-patterns suggest src/ --priority=high# Evaluate specific file
/design-patterns evaluate src/services/api-client.ts
# Evaluate all singletons
/design-patterns evaluate src/ --pattern=singleton
# Full quality report
/design-patterns evaluate src/ --detailedThis skill can be inherited by:
refactoring-specialist.md → Provides pattern knowledge for refactoringcode-reviewer.md → Adds pattern detection to review processarchitecture-advisor.md → Informs architectural decisions with pattern usagereference/patterns-index.yaml → Machine-readable index of 23 patterns with metadatareference/creational.md → Creational patterns documentationreference/structural.md → Structural patterns documentationreference/behavioral.md → Behavioral patterns documentationsignatures/detection-rules.yaml → Regex patterns and heuristics for detectionsignatures/code-smells.yaml → Mapping from code smells to applicable patternssignatures/stack-patterns.yaml → Stack detection rules and native pattern equivalentschecklists/pattern-evaluation.md → Quality evaluation criteria and scoring guidelinesSkill Version: 1.0.0 Pattern Coverage: 23 GoF patterns Supported Stacks: 8 (React, Angular, NestJS, Vue, Express, RxJS, Redux/Zustand, ORMs) Last Updated: 2026-01-21
352e748
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.