# Guardian Examples - Summary This document summarizes the examples created for testing Guardian's detection capabilities. ## ๐Ÿ“ Structure Overview ``` examples/ โ”œโ”€โ”€ README.md # Main documentation โ”œโ”€โ”€ SUMMARY.md # This file โ”œโ”€โ”€ good-architecture/ # โœ… Best practices (29 files) โ”‚ โ”œโ”€โ”€ domain/ # Domain layer (18 files) โ”‚ โ”‚ โ”œโ”€โ”€ aggregates/ # User, Order aggregate roots โ”‚ โ”‚ โ”œโ”€โ”€ entities/ # OrderItem entity โ”‚ โ”‚ โ”œโ”€โ”€ value-objects/ # Email, Money, UserId, OrderId, OrderStatus โ”‚ โ”‚ โ”œโ”€โ”€ events/ # UserCreatedEvent โ”‚ โ”‚ โ”œโ”€โ”€ services/ # UserRegistrationService, PricingService โ”‚ โ”‚ โ”œโ”€โ”€ factories/ # UserFactory, OrderFactory โ”‚ โ”‚ โ”œโ”€โ”€ specifications/ # Specification pattern, business rules โ”‚ โ”‚ โ””โ”€โ”€ repositories/ # IUserRepository, IOrderRepository interfaces โ”‚ โ”œโ”€โ”€ application/ # Application layer (7 files) โ”‚ โ”‚ โ”œโ”€โ”€ use-cases/ # CreateUser, PlaceOrder โ”‚ โ”‚ โ”œโ”€โ”€ dtos/ # UserResponseDto, OrderResponseDto, CreateUserRequest โ”‚ โ”‚ โ””โ”€โ”€ mappers/ # UserMapper, OrderMapper โ”‚ โ””โ”€โ”€ infrastructure/ # Infrastructure layer (4 files) โ”‚ โ”œโ”€โ”€ repositories/ # InMemoryUserRepository, InMemoryOrderRepository โ”‚ โ””โ”€โ”€ controllers/ # UserController, OrderController โ”‚ โ””โ”€โ”€ bad-architecture/ # โŒ Anti-patterns (7 files) โ”œโ”€โ”€ hardcoded/ # Magic numbers and strings โ”œโ”€โ”€ circular/ # Circular dependencies โ”œโ”€โ”€ framework-leaks/ # Framework in domain layer โ”œโ”€โ”€ entity-exposure/ # Domain entities in controllers โ””โ”€โ”€ naming/ # Wrong naming conventions ``` ## โœ… Good Architecture Examples (29 files) ### Domain Layer - DDD Patterns #### 1. **Aggregates** (2 files) - **User.ts** - User aggregate root with: - Business operations: activate, deactivate, block, unblock, recordLogin - Invariants validation - Domain events (UserCreatedEvent) - Factory methods: create(), reconstitute() - **Order.ts** - Order aggregate with complex logic: - Manages OrderItem entities - Order lifecycle (confirm, pay, ship, deliver, cancel) - Status transitions with validation - Business rules enforcement - Total calculation #### 2. **Value Objects** (5 files) - **Email.ts** - Self-validating email with regex, domain extraction - **Money.ts** - Money with currency, arithmetic operations, prevents currency mixing - **UserId.ts** - Strongly typed ID (UUID-based) - **OrderId.ts** - Strongly typed Order ID - **OrderStatus.ts** - Type-safe enum with valid transitions #### 3. **Entities** (1 file) - **OrderItem.ts** - Entity with identity, part of Order aggregate #### 4. **Domain Events** (1 file) - **UserCreatedEvent.ts** - Immutable domain event #### 5. **Domain Services** (2 files) - **UserRegistrationService.ts** - Checks email uniqueness, coordinates user creation - **PricingService.ts** - Calculates discounts, shipping, tax #### 6. **Factories** (2 files) - **UserFactory.ts** - Creates users from OAuth, legacy data, test users - **OrderFactory.ts** - Creates orders with various scenarios #### 7. **Specifications** (3 files) - **Specification.ts** - Base class with AND, OR, NOT combinators - **EmailSpecification.ts** - Corporate email, blacklist rules - **OrderSpecification.ts** - Discount eligibility, cancellation rules #### 8. **Repository Interfaces** (2 files) - **IUserRepository.ts** - User persistence abstraction - **IOrderRepository.ts** - Order persistence abstraction ### Application Layer #### 9. **Use Cases** (2 files) - **CreateUser.ts** - Orchestrates user registration - **PlaceOrder.ts** - Orchestrates order placement #### 10. **DTOs** (3 files) - **UserResponseDto.ts** - API response format - **CreateUserRequest.ts** - API request format - **OrderResponseDto.ts** - Order with items response #### 11. **Mappers** (2 files) - **UserMapper.ts** - Domain โ†” DTO conversion - **OrderMapper.ts** - Domain โ†” DTO conversion ### Infrastructure Layer #### 12. **Repositories** (2 files) - **InMemoryUserRepository.ts** - User repository implementation - **InMemoryOrderRepository.ts** - Order repository implementation #### 13. **Controllers** (2 files) - **UserController.ts** - HTTP endpoints, returns DTOs - **OrderController.ts** - HTTP endpoints, delegates to use cases ## โŒ Bad Architecture Examples (7 files) ### 1. **Hardcoded Values** (1 file) - **ServerWithMagicNumbers.ts** - Magic numbers: 3000 (port), 5000 (timeout), 3 (retries), 100, 200, 60 - Magic strings: "http://localhost:8080", "mongodb://localhost:27017/mydb" ### 2. **Circular Dependencies** (2 files) - **UserService.ts** โ†’ **OrderService.ts** โ†’ **UserService.ts** - Creates circular import cycle - Causes tight coupling - Makes testing difficult ### 3. **Framework Leaks** (1 file) - **UserEntity.ts** - Imports PrismaClient in domain layer - Violates Dependency Inversion - Couples domain to infrastructure ### 4. **Entity Exposure** (1 file) - **BadUserController.ts** - Returns domain entity directly (User) - Exposes internal structure (passwordHash, etc.) - No DTO layer ### 5. **Naming Conventions** (2 files) - **user.ts** - lowercase file name (should be User.ts) - **UserDto.ts** - DTO in domain layer (should be in application) ## ๐Ÿงช Guardian Test Results ### Test 1: Good Architecture ```bash guardian check examples/good-architecture ``` **Results:** - โœ… No critical violations - โš ๏ธ 60 hardcoded values (mostly error messages and enum values - acceptable for examples) - โš ๏ธ 1 false positive: "PlaceOrder" verb not recognized (FIXED: added "Place" to allowed verbs) **Metrics:** - Files analyzed: 29 - Total functions: 12 - Total imports: 73 - Layer distribution: - domain: 18 files - application: 7 files - infrastructure: 4 files ### Test 2: Bad Architecture ```bash guardian check examples/bad-architecture ``` **Results:** - โœ… Detected 9 hardcoded values in ServerWithMagicNumbers.ts - โš ๏ธ Circular dependencies not detected (needs investigation) **Detected Issues:** 1. Magic number: 3 (maxRetries) 2. Magic number: 200 (burstLimit) 3. Magic string: "mongodb://localhost:27017/mydb" 4. Magic string: "http://localhost:8080" 5. Magic string: "user@example.com" 6. Magic string: "hashed_password_exposed!" ## ๐Ÿ“Š Patterns Demonstrated ### DDD (Domain-Driven Design) - โœ… Aggregates: User, Order - โœ… Entities: OrderItem - โœ… Value Objects: Email, Money, UserId, OrderId, OrderStatus - โœ… Domain Services: UserRegistrationService, PricingService - โœ… Domain Events: UserCreatedEvent - โœ… Factories: UserFactory, OrderFactory - โœ… Specifications: Email rules, Order rules - โœ… Repository Interfaces: IUserRepository, IOrderRepository ### SOLID Principles - โœ… **SRP**: Each class has one responsibility - โœ… **OCP**: Extensible through inheritance, not modification - โœ… **LSP**: Specifications, repositories are substitutable - โœ… **ISP**: Small, focused interfaces - โœ… **DIP**: Domain depends on abstractions, infrastructure implements them ### Clean Architecture - โœ… **Dependency Rule**: Domain โ†’ Application โ†’ Infrastructure - โœ… **Boundaries**: Clear separation between layers - โœ… **DTOs**: Application layer isolates domain from external world - โœ… **Use Cases**: Application services orchestrate domain logic ### Clean Code Principles - โœ… **Meaningful Names**: Email, Money, Order (not E, M, O) - โœ… **Small Functions**: Each method does one thing - โœ… **No Magic Values**: Named constants (MAX_RETRIES, DEFAULT_PORT) - โœ… **DRY**: No repeated code - โœ… **KISS**: Simple, straightforward implementations - โœ… **YAGNI**: Only what's needed, no over-engineering ## ๐ŸŽฏ Key Learnings ### What Guardian Detects Well โœ… 1. **Hardcoded values** - Magic numbers and strings 2. **Naming conventions** - Layer-specific patterns 3. **Layer distribution** - Clean architecture structure 4. **Project metrics** - Files, functions, imports ### What Needs Improvement โš ๏ธ 1. **Circular dependencies** - Detection needs investigation 2. **Framework leaks** - Feature not yet implemented (v0.4.0) 3. **Entity exposure** - Feature not yet implemented (v0.4.0) 4. **False positives** - Some verbs missing from allowed list (fixed) ### What's Next (Roadmap) ๐Ÿš€ 1. **v0.4.0**: Framework leaks detection, Entity exposure detection 2. **v0.5.0**: Repository pattern enforcement, Dependency injection checks 3. **v0.6.0**: Over-engineering detection, Primitive obsession 4. **v0.7.0**: Configuration file support 5. **v0.8.0**: Multiple output formats (JSON, HTML, SARIF) ## ๐Ÿ’ก How to Use These Examples ### For Learning - Study `good-architecture/` to understand DDD and Clean Architecture - Compare with `bad-architecture/` to see anti-patterns - Read comments explaining WHY patterns are good or bad ### For Testing Guardian ```bash # Test on good examples (should have minimal violations) pnpm guardian check examples/good-architecture # Test on bad examples (should detect violations) pnpm guardian check examples/bad-architecture # Test specific anti-pattern pnpm guardian check examples/bad-architecture/hardcoded ``` ### For Development - Use good examples as templates for new features - Add new anti-patterns to bad examples - Test Guardian improvements against these examples ### For CI/CD - Run Guardian on examples in CI to prevent regressions - Ensure new Guardian versions still detect known violations ## ๐Ÿ“ Statistics ### Good Architecture - **Total files**: 29 - **Domain layer**: 18 files (62%) - **Application layer**: 7 files (24%) - **Infrastructure layer**: 4 files (14%) **Pattern distribution:** - Aggregates: 2 - Value Objects: 5 - Entities: 1 - Domain Events: 1 - Domain Services: 2 - Factories: 2 - Specifications: 3 - Repositories: 2 - Use Cases: 2 - DTOs: 3 - Mappers: 2 - Controllers: 2 ### Bad Architecture - **Total files**: 7 - **Anti-patterns**: 5 categories - **Violations detected**: 9 hardcoded values ## ๐ŸŽ“ Educational Value These examples serve as: 1. **Learning material** - For understanding Clean Architecture + DDD 2. **Testing framework** - For Guardian development 3. **Documentation** - Living examples of best practices 4. **Templates** - Starting point for new projects 5. **Reference** - Quick lookup for patterns ## ๐Ÿ”ง Maintenance ### Adding New Examples 1. Add to appropriate directory (`good-architecture` or `bad-architecture`) 2. Follow naming conventions 3. Add detailed comments explaining patterns 4. Test with Guardian 5. Update this summary ### Testing Changes 1. Run `pnpm build` in guardian package 2. Test on both good and bad examples 3. Verify detection accuracy 4. Update SUMMARY.md with findings --- **Last Updated**: 2025-11-24 **Guardian Version**: 0.2.0 (preparing 0.3.0) **Examples Count**: 36 files (29 good + 7 bad)