Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:56:23 +08:00
commit 4292614d3a
9 changed files with 1320 additions and 0 deletions

View File

@@ -0,0 +1,158 @@
---
name: code-quality
description: Expert code quality engineering covering clean code principles, SOLID, DRY, KISS, YAGNI, code smells, refactoring patterns, static analysis, linting, code coverage, mutation testing, and software craftsmanship. Activates for code quality, clean code, SOLID principles, code smells, refactoring, technical debt, code review, linting, eslint, prettier, static analysis, code coverage.
allowed-tools: Read, Grep, Glob
---
# Code Quality Expert
Master of clean code principles, SOLID, and software craftsmanship.
## SOLID Principles
**Single Responsibility**:
```typescript
// ❌ Bad: Multiple responsibilities
class User {
save() { /* database logic */ }
sendEmail() { /* email logic */ }
hashPassword() { /* crypto logic */ }
}
// ✅ Good: Single responsibility
class User { /* user data only */ }
class UserRepository { save(user: User) {} }
class EmailService { send(to: string, message: string) {} }
class PasswordHasher { hash(password: string) {} }
```
**Open/Closed**:
```typescript
// ✅ Open for extension, closed for modification
interface PaymentMethod {
processPayment(amount: number): Promise<void>;
}
class CreditCardPayment implements PaymentMethod {
async processPayment(amount: number) { /* ... */ }
}
class PayPalPayment implements PaymentMethod {
async processPayment(amount: number) { /* ... */ }
}
// Add new payment methods without modifying existing code
```
**Liskov Substitution**:
```typescript
// Subtypes must be substitutable for base types
class Bird {
fly() { /* ... */ }
}
// ❌ Bad: Penguin can't fly, violates LSP
class Penguin extends Bird {
fly() { throw new Error('Cannot fly'); }
}
// ✅ Good: Proper abstraction
interface Bird {}
interface FlyingBird extends Bird { fly(): void; }
class Sparrow implements FlyingBird { fly() {} }
class Penguin implements Bird {} // No fly method
```
**Interface Segregation**:
```typescript
// ❌ Bad: Fat interface
interface Worker {
work(): void;
eat(): void;
sleep(): void;
}
// ✅ Good: Segregated interfaces
interface Workable { work(): void; }
interface Eatable { eat(): void; }
interface Sleepable { sleep(): void; }
class Human implements Workable, Eatable, Sleepable {}
class Robot implements Workable {} // Doesn't need eat/sleep
```
**Dependency Inversion**:
```typescript
// ❌ Bad: High-level depends on low-level
class EmailService {
private smtp = new SMTPClient(); // Direct dependency
}
// ✅ Good: Depend on abstraction
interface EmailClient {
send(to: string, message: string): Promise<void>;
}
class EmailService {
constructor(private client: EmailClient) {}
}
```
## Clean Code Principles
**DRY (Don't Repeat Yourself)**:
```typescript
// ❌ Duplication
function validateEmail(email: string) {
return /^\S+@\S+\.\S+$/.test(email);
}
function validateUserEmail(email: string) {
return /^\S+@\S+\.\S+$/.test(email); // Duplicate
}
// ✅ Single source of truth
const EMAIL_REGEX = /^\S+@\S+\.\S+$/;
const isValidEmail = (email: string) => EMAIL_REGEX.test(email);
```
**KISS (Keep It Simple)**:
```typescript
// ❌ Over-engineered
class AdvancedCalculatorFactoryBuilderSingleton {
private static instance: AdvancedCalculatorFactoryBuilderSingleton;
// 50 lines of unnecessary abstraction
}
// ✅ Simple
const add = (a: number, b: number) => a + b;
```
**YAGNI (You Aren't Gonna Need It)**:
```typescript
// ❌ Premature abstraction
class User {
futureFeature1() {} // Not used yet
futureFeature2() {} // Not used yet
futureFeature3() {} // Not used yet
}
// ✅ Only what's needed now
class User {
getCurrentFeatures() {} // Actually used
}
```
## Code Smells
**Long Method**: > 50 lines → Extract methods
**Large Class**: > 300 lines → Extract classes
**Long Parameter List**: > 3 params → Parameter object
**Primitive Obsession**: Use value objects
**Data Clumps**: Group related data
**Switch Statements**: Replace with polymorphism
## Testing Strategies
**Test Coverage**: 80%+ for critical paths
**Mutation Testing**: Ensure test quality
**Test Pyramid**: Many unit, few integration, minimal E2E

View File

@@ -0,0 +1,245 @@
---
name: design-patterns
description: Expert knowledge of Gang of Four (GoF) design patterns including creational (Singleton, Factory, Builder, Prototype), structural (Adapter, Decorator, Proxy, Facade), and behavioral (Strategy, Observer, Command, Template Method, Chain of Responsibility). Modern TypeScript/JavaScript implementations with real-world use cases. Activates for design patterns, factory pattern, singleton, strategy pattern, observer pattern, decorator pattern, adapter pattern, builder pattern, proxy pattern, facade pattern, template method.
allowed-tools: Read, Grep, Glob
---
# Design Patterns Expert
Master of GoF design patterns with modern TypeScript implementations.
## Creational Patterns
**Factory Pattern**:
```typescript
interface Animal {
speak(): string;
}
class Dog implements Animal {
speak() { return 'Woof!'; }
}
class Cat implements Animal {
speak() { return 'Meow!'; }
}
class AnimalFactory {
static create(type: 'dog' | 'cat'): Animal {
switch (type) {
case 'dog': return new Dog();
case 'cat': return new Cat();
}
}
}
```
**Singleton Pattern**:
```typescript
class Database {
private static instance: Database;
private constructor() {} // Private constructor
static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
```
**Builder Pattern**:
```typescript
class UserBuilder {
private user: Partial<User> = {};
setName(name: string) {
this.user.name = name;
return this;
}
setEmail(email: string) {
this.user.email = email;
return this;
}
build(): User {
if (!this.user.name || !this.user.email) {
throw new Error('Missing required fields');
}
return this.user as User;
}
}
// Usage
const user = new UserBuilder()
.setName('John')
.setEmail('john@example.com')
.build();
```
## Structural Patterns
**Adapter Pattern**:
```typescript
// Old API
class OldLogger {
logMessage(message: string) { console.log(message); }
}
// New interface
interface Logger {
log(level: string, message: string): void;
}
// Adapter
class LoggerAdapter implements Logger {
constructor(private oldLogger: OldLogger) {}
log(level: string, message: string) {
this.oldLogger.logMessage(`[${level}] ${message}`);
}
}
```
**Decorator Pattern**:
```typescript
interface Coffee {
cost(): number;
description(): string;
}
class SimpleCoffee implements Coffee {
cost() { return 5; }
description() { return 'Simple coffee'; }
}
class MilkDecorator implements Coffee {
constructor(private coffee: Coffee) {}
cost() { return this.coffee.cost() + 2; }
description() { return this.coffee.description() + ', milk'; }
}
// Usage
let coffee: Coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee.cost(); // 7
```
**Proxy Pattern**:
```typescript
class RealImage {
constructor(private filename: string) {
this.loadFromDisk();
}
private loadFromDisk() {
console.log('Loading:', this.filename);
}
display() {
console.log('Displaying:', this.filename);
}
}
class ProxyImage {
private realImage?: RealImage;
constructor(private filename: string) {}
display() {
if (!this.realImage) {
this.realImage = new RealImage(this.filename); // Lazy loading
}
this.realImage.display();
}
}
```
## Behavioral Patterns
**Strategy Pattern**:
```typescript
interface SortStrategy {
sort(data: number[]): number[];
}
class QuickSort implements SortStrategy {
sort(data: number[]) { /* quicksort */ return data; }
}
class MergeSort implements SortStrategy {
sort(data: number[]) { /* mergesort */ return data; }
}
class Sorter {
constructor(private strategy: SortStrategy) {}
setStrategy(strategy: SortStrategy) {
this.strategy = strategy;
}
sort(data: number[]) {
return this.strategy.sort(data);
}
}
```
**Observer Pattern**:
```typescript
interface Observer {
update(data: any): void;
}
class Subject {
private observers: Observer[] = [];
attach(observer: Observer) {
this.observers.push(observer);
}
notify(data: any) {
this.observers.forEach(o => o.update(data));
}
}
class EmailObserver implements Observer {
update(data: any) {
console.log('Sending email:', data);
}
}
```
**Command Pattern**:
```typescript
interface Command {
execute(): void;
undo(): void;
}
class SaveCommand implements Command {
constructor(private editor: Editor) {}
execute() { this.editor.save(); }
undo() { this.editor.restore(); }
}
class CommandInvoker {
private history: Command[] = [];
execute(command: Command) {
command.execute();
this.history.push(command);
}
undo() {
const command = this.history.pop();
command?.undo();
}
}
```
Apply design patterns to solve common problems elegantly!

View File

@@ -0,0 +1,84 @@
---
name: software-architecture
description: Expert software architecture covering architectural patterns (microservices, monolith, event-driven, CQRS), scalability, distributed systems, CAP theorem, database architecture, API design, system design, domain-driven design (DDD), hexagonal architecture, and architecture decision records (ADRs). Activates for software architecture, system design, microservices, monolith, event-driven, CQRS, scalability, distributed systems, CAP theorem, DDD, hexagonal architecture, ADR.
allowed-tools: Read, Grep, Glob
---
# Software Architecture Expert
Master of architectural patterns, system design, and scalability.
## Architectural Patterns
**Layered Architecture**:
```
Presentation Layer (UI)
Business Logic Layer (Services)
Data Access Layer (Repositories)
Database
```
**Hexagonal Architecture (Ports & Adapters)**:
```typescript
// Core Domain (business logic, no dependencies)
interface PaymentPort {
process(amount: number): Promise<void>;
}
// Adapter (infrastructure)
class StripeAdapter implements PaymentPort {
async process(amount: number) { /* Stripe API */ }
}
// Application uses port, not concrete implementation
class CheckoutService {
constructor(private payment: PaymentPort) {}
}
```
**Event-Driven Architecture**:
```typescript
// Producer
eventBus.publish({ type: 'OrderPlaced', orderId: '123' });
// Consumers (decoupled)
eventBus.subscribe('OrderPlaced', inventoryService.reserve);
eventBus.subscribe('OrderPlaced', emailService.notify);
```
**CQRS** (Command Query Responsibility Segregation):
- Commands: Write operations, change state
- Queries: Read operations, no side effects
- Separate models for read/write optimization
## Scalability Patterns
**Horizontal Scaling**: Add more servers
**Vertical Scaling**: Bigger server
**Caching**: Redis, CDN, application cache
**Database Sharding**: Partition by key (user_id, region)
**Read Replicas**: Offload read traffic
**Load Balancing**: Distribute traffic evenly
## CAP Theorem
**Consistency**: All nodes see same data
**Availability**: Every request gets response
**Partition Tolerance**: System works despite network failures
Can only guarantee 2 of 3:
- **CP**: Consistent + Partition-tolerant (sacrifice availability)
- **AP**: Available + Partition-tolerant (eventual consistency)
- **CA**: Consistent + Available (no partition tolerance, single node)
## Domain-Driven Design
**Ubiquitous Language**: Shared vocabulary
**Bounded Contexts**: Explicit boundaries
**Aggregates**: Consistency boundaries
**Entities**: Objects with identity
**Value Objects**: Immutable, no identity
**Domain Events**: Business occurrences