{"skill":{"slug":"nm-conserve-code-quality-principles","displayName":"Nm Conserve Code Quality Principles","summary":"Applies KISS, YAGNI, and SOLID principles for clean code with reduced complexity","description":"---\nname: code-quality-principles\ndescription: Applies KISS, YAGNI, and SOLID principles for clean code with reduced complexity\nversion: 1.9.8\ntriggers:\n  - design\n  - principles\n  - clean-code\n  - architecture\n  - refactoring or reviewing code for over-engineering\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/conserve\", \"emoji\": \"\\ud83e\\udd9e\"}}\nsource: claude-night-market\nsource_plugin: conserve\n---\n\n> **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n# Code Quality Principles\n\nGuidance on KISS, YAGNI, and SOLID principles with language-specific examples.\n\n\n## When To Use\n\n- Improving code readability and maintainability\n- Applying SOLID, KISS, YAGNI principles during refactoring\n\n## When NOT To Use\n\n- Throwaway scripts or one-time data migrations\n- Performance-critical code where readability trades are justified\n\n## KISS (Keep It Simple, Stupid)\n\n**Principle**: Avoid unnecessary complexity. Prefer obvious solutions over clever ones.\n\n### Guidelines\n\n| Prefer | Avoid |\n|--------|-------|\n| Simple conditionals | Complex regex for simple checks |\n| Explicit code | Magic numbers/strings |\n| Standard patterns | Clever shortcuts |\n| Direct solutions | Over-abstracted layers |\n\n### Python Example\n\n```python\n# Bad: Overly clever one-liner\nusers = [u for u in (db.get(id) for id in ids) if u and u.active and not u.banned]\n\n# Good: Clear and readable\nusers = []\nfor user_id in ids:\n    user = db.get(user_id)\n    if user and user.active and not user.banned:\n        users.append(user)\n```\n\n### Rust Example\n\n```rust\n// Bad: Unnecessary complexity\nfn process(data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {\n    data.iter()\n        .map(|&b| b.checked_add(1).ok_or(\"overflow\"))\n        .collect::<Result<Vec<_>, _>>()\n        .map_err(|e| e.into())\n}\n\n// Good: Simple and clear\nfn process(data: &[u8]) -> Result<Vec<u8>, &'static str> {\n    let mut result = Vec::with_capacity(data.len());\n    for &byte in data {\n        result.push(byte.checked_add(1).ok_or(\"overflow\")?);\n    }\n    Ok(result)\n}\n```\n\n## YAGNI (You Aren't Gonna Need It)\n\n**Principle**: Don't implement features until they are actually needed.\n\n### Guidelines\n\n| Do | Don't |\n|----|-------|\n| Solve current problem | Build for hypothetical futures |\n| Add when 3rd use case appears | Create abstractions for 1 use case |\n| Delete dead code | Keep \"just in case\" code |\n| Minimal viable solution | Premature optimization |\n\n### Python Example\n\n```python\n# Bad: Premature abstraction for one use case\nclass AbstractDataProcessor:\n    def process(self, data): ...\n    def validate(self, data): ...\n    def transform(self, data): ...\n\nclass CSVProcessor(AbstractDataProcessor):\n    def process(self, data):\n        return self.transform(self.validate(data))\n\n# Good: Simple function until more cases appear\ndef process_csv(data: list[str]) -> list[dict]:\n    return [parse_row(row) for row in data if row.strip()]\n```\n\n### TypeScript Example\n\n```typescript\n// Bad: Over-engineered config system\ninterface ConfigProvider<T> {\n  get<K extends keyof T>(key: K): T[K];\n  set<K extends keyof T>(key: K, value: T[K]): void;\n  watch<K extends keyof T>(key: K, callback: (v: T[K]) => void): void;\n}\n\n// Good: Simple config for current needs\nconst config = {\n  apiUrl: process.env.API_URL || 'http://localhost:3000',\n  timeout: 5000,\n};\n```\n\n## SOLID Principles\n\n### Single Responsibility Principle\n\nEach module/class should have one reason to change.\n\n```python\n# Bad: Multiple responsibilities\nclass UserManager:\n    def create_user(self, data): ...\n    def send_welcome_email(self, user): ...  # Email responsibility\n    def generate_report(self, users): ...     # Reporting responsibility\n\n# Good: Separated responsibilities\nclass UserRepository:\n    def create(self, data): ...\n\nclass EmailService:\n    def send_welcome(self, user): ...\n\nclass UserReportGenerator:\n    def generate(self, users): ...\n```\n\n### Open/Closed Principle\n\nOpen for extension, closed for modification.\n\n```python\n# Bad: Requires modification for new types\ndef calculate_area(shape):\n    if shape.type == \"circle\":\n        return 3.14 * shape.radius ** 2\n    elif shape.type == \"rectangle\":\n        return shape.width * shape.height\n    # Must modify to add new shapes\n\n# Good: Extensible without modification\nfrom abc import ABC, abstractmethod\n\nclass Shape(ABC):\n    @abstractmethod\n    def area(self) -> float: ...\n\nclass Circle(Shape):\n    def __init__(self, radius: float):\n        self.radius = radius\n    def area(self) -> float:\n        return 3.14 * self.radius ** 2\n```\n\n### Liskov Substitution Principle\n\nSubtypes must be substitutable for their base types.\n\n```python\n# Bad: Violates LSP - Square changes Rectangle behavior\nclass Rectangle:\n    def set_width(self, w): self.width = w\n    def set_height(self, h): self.height = h\n\nclass Square(Rectangle):  # Breaks when used as Rectangle\n    def set_width(self, w):\n        self.width = self.height = w  # Unexpected side effect\n\n# Good: Separate types with common interface\nclass Shape(ABC):\n    @abstractmethod\n    def area(self) -> float: ...\n\nclass Rectangle(Shape):\n    def __init__(self, width: float, height: float): ...\n\nclass Square(Shape):\n    def __init__(self, side: float): ...\n```\n\n### Interface Segregation Principle\n\nClients shouldn't depend on interfaces they don't use.\n\n```typescript\n// Bad: Fat interface\ninterface Worker {\n  work(): void;\n  eat(): void;\n  sleep(): void;\n}\n\n// Good: Segregated interfaces\ninterface Workable {\n  work(): void;\n}\n\ninterface Feedable {\n  eat(): void;\n}\n\n// Clients only implement what they need\nclass Robot implements Workable {\n  work(): void { /* ... */ }\n}\n```\n\n### Dependency Inversion Principle\n\nDepend on abstractions, not concretions.\n\n```python\n# Bad: Direct dependency on concrete class\nclass OrderService:\n    def __init__(self):\n        self.db = PostgresDatabase()  # Tight coupling\n\n# Good: Depend on abstraction\nfrom abc import ABC, abstractmethod\n\nclass Database(ABC):\n    @abstractmethod\n    def save(self, data): ...\n\nclass OrderService:\n    def __init__(self, db: Database):\n        self.db = db  # Injected abstraction\n```\n\n## Quick Reference\n\n| Principle | Question to Ask | Red Flag |\n|-----------|-----------------|----------|\n| KISS | \"Is there a simpler way?\" | Complex solution for simple problem |\n| YAGNI | \"Do I need this right now?\" | Building for hypothetical use cases |\n| SRP | \"What's the one reason to change?\" | Class doing multiple jobs |\n| OCP | \"Can I extend without modifying?\" | Switch statements for types |\n| LSP | \"Can subtypes replace base types?\" | Overridden methods with side effects |\n| ISP | \"Does client need all methods?\" | Empty method implementations |\n| DIP | \"Am I depending on abstractions?\" | `new` keyword in business logic |\n\n## When Principles Conflict\n\n1. **KISS vs SOLID**: For small projects, KISS wins. Add SOLID patterns as complexity grows.\n2. **YAGNI vs DIP**: Don't add abstractions until you have 2+ implementations.\n3. **Readability vs DRY**: Prefer slight duplication over wrong abstraction.\n\n## Integration with Code Review\n\nWhen reviewing code, check:\n- [ ] No unnecessary complexity (KISS)\n- [ ] No speculative features (YAGNI)\n- [ ] Each class has single responsibility (SRP)\n- [ ] No god classes (> 500 lines)\n- [ ] Dependencies are injected, not created (DIP)\n\n**Verification:** Run `wc -l <file>` to check line counts and `rg -c \"class \" <file>` (or `grep -c \"class \" <file>`) to count classes per file.\n\n## Related Skills\n\n- `imbue:karpathy-principles` - The \"Simplicity First\" principle wraps KISS, YAGNI, and SOLID into a four-principle synthesis derived from Karpathy's observations on LLM coding pitfalls\n- See `docs/quality-gates.md#skill-level-quality-gate-composition` for the full gate-skill federation graph\n","tags":{"latest":"1.0.3"},"stats":{"comments":0,"downloads":644,"installsAllTime":1,"installsCurrent":1,"stars":0,"versions":4},"createdAt":1775901703772,"updatedAt":1780867480919},"latestVersion":{"version":"1.0.3","createdAt":1780867480919,"changelog":"Release v1.9.11","license":"MIT-0"},"metadata":{"setup":[],"os":null,"systems":null},"owner":{"handle":"athola","userId":"s17emme0e2m3cpf7k2jvp3a84984b8z9","displayName":"athola","image":"https://avatars.githubusercontent.com/u/9769290?v=4"},"moderation":null}