Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

: '

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

;\n const decimals = type === 'salary' ? 0 : 2;\n const prefix = type === 'price' ? '' : ' ';\n\n return `${prefix}${symbol}${value.toFixed(decimals)}`;\n}\n\n// Now price formatting changes require checking salary and discount logic\n// And discount needs a negative sign but price doesn't\n// The abstraction becomes a mess of special cases\n```\n\n**Correct (explicit duplication until patterns emerge):**\n\n```typescript\nfunction formatPrice(cents: number): string {\n return `${(cents / 100).toFixed(2)}`;\n}\n\nfunction formatSalary(annual: number): string {\n return `${annual.toLocaleString()}`;\n}\n\nfunction formatDiscount(cents: number): string {\n return `-${(cents / 100).toFixed(2)}`;\n}\n\n// Each can evolve independently\n// formatPrice might add currency symbols later\n// formatSalary might add \"per year\" suffix\n// formatDiscount might show percentage instead\n```\n\n### The Sandi Metz Rule\n\n\"Duplication is far cheaper than the wrong abstraction.\" If you're unsure whether code should be shared:\n\n1. Duplicate it\n2. Wait for the third occurrence\n3. Look for the true underlying pattern\n4. Then extract with confidence\n\n### When Abstraction IS Appropriate\n\n- Business rule that must be consistent (tax calculation, authentication)\n- Algorithm that is complex and needs isolated testing\n- Pattern that has appeared 3+ times with identical structure\n- Domain concept with a clear name in the ubiquitous language\n\n### Benefits\n\n- Code changes are localized to one area\n- New requirements don't break unrelated features\n- Easier to understand - each module is self-contained\n- Refactoring is straightforward when patterns emerge\n\n### 6.5 Use Data-Driven Patterns Over Repetitive Conditionals\n\nWhen you have repetitive if/else or switch statements that map inputs to outputs, replace them with data structures like maps, lookup tables, or configuration objects. Data-driven code is easier to extend (add a line, not a branch), easier to test (validate the data structure), and less prone to copy-paste errors.\n\n**Incorrect (repetitive conditionals):**\n\n```typescript\nfunction getStatusColor(status: string): string {\n if (status === 'pending') {\n return '#FFA500';\n } else if (status === 'approved') {\n return '#00FF00';\n } else if (status === 'rejected') {\n return '#FF0000';\n } else if (status === 'cancelled') {\n return '#808080';\n } else if (status === 'processing') {\n return '#0000FF';\n } else if (status === 'completed') {\n return '#00AA00';\n } else {\n return '#000000';\n }\n}\n// Adding a new status = new branch + risk of typo\n```\n\n**Correct (data-driven lookup):**\n\n```typescript\nconst STATUS_COLORS: Record\u003cstring, string> = {\n pending: '#FFA500',\n approved: '#00FF00',\n rejected: '#FF0000',\n cancelled: '#808080',\n processing: '#0000FF',\n completed: '#00AA00',\n};\n\nfunction getStatusColor(status: string): string {\n return STATUS_COLORS[status] ?? '#000000';\n}\n// Adding a new status = one line in the map\n```\n\n### When NOT to Use Data-Driven\n\n- When branches have complex logic, not just value mapping\n- When there are only 2-3 cases and they're unlikely to grow\n- When the \"data\" would be as complex as the code it replaces\n\n### Benefits\n\n- Adding new cases is a configuration change, not code change\n- Data can be loaded from external sources (database, config files)\n- Easier to test - validate the data structure separately\n- Business rules are visible at a glance in the data structure\n- Reduces cyclomatic complexity significantly\n\n---\n\n## 7. Dead Code Elimination (MEDIUM)\n\nRemove unused code, redundant comments, and obsolete patterns. Delete rather than comment out. Keep comments that explain \"why\" not \"what\".\n\n### 7.1 Delete Unused Code Artifacts\n\nUnused variables, functions, imports, and parameters are noise that obscures the real logic. They force readers to track dead references, bloat bundle sizes, and create phantom dependencies that complicate refactoring. Modern tooling catches unused code - delete it immediately rather than leaving it \"just in case.\"\n\n**Incorrect (unused artifacts throughout):**\n\n```typescript\nimport { useState, useEffect, useCallback, useMemo } from 'react';\nimport { formatDate, parseDate, isValidDate } from './dateUtils';\nimport { API_URL, MAX_RETRIES, TIMEOUT } from './constants';\n\ninterface UserListProps {\n users: User[];\n onSelect: (user: User) => void;\n showAvatar: boolean; // Never used in component\n maxItems: number; // Never used in component\n}\n\nexport function UserList({ users, onSelect, showAvatar, maxItems }: UserListProps) {\n const [selectedId, setSelectedId] = useState\u003cstring | null>(null);\n const [isLoading, setIsLoading] = useState(false); // Never used\n const [error, setError] = useState\u003cError | null>(null); // Never used\n\n const sortedUsers = useMemo(() => users, [users]); // Memo does nothing\n\n const handleClick = useCallback((user: User) => {\n setSelectedId(user.id);\n onSelect(user);\n }, [onSelect]);\n\n const unusedHelper = (data: unknown) => { // Never called\n return formatDate(data as Date);\n };\n\n return (\n \u003cul>\n {sortedUsers.map(user => (\n \u003cli key={user.id} onClick={() => handleClick(user)}>\n {user.name}\n \u003c/li>\n ))}\n \u003c/ul>\n );\n}\n```\n\n**Correct (only what's needed):**\n\n```typescript\nimport { useState, useCallback } from 'react';\n\ninterface UserListProps {\n users: User[];\n onSelect: (user: User) => void;\n}\n\nexport function UserList({ users, onSelect }: UserListProps) {\n const [selectedId, setSelectedId] = useState\u003cstring | null>(null);\n\n const handleClick = useCallback((user: User) => {\n setSelectedId(user.id);\n onSelect(user);\n }, [onSelect]);\n\n return (\n \u003cul>\n {users.map(user => (\n \u003cli key={user.id} onClick={() => handleClick(user)}>\n {user.name}\n \u003c/li>\n ))}\n \u003c/ul>\n );\n}\n```\n\n### When NOT to Apply\n\n- Interface compliance requires the parameter signature (use underscore prefix)\n- Public API where removal would be a breaking change\n- Parameters used only in debug/logging modes\n- Imports used only in type annotations (may appear unused to some tools)\n\n### Benefits\n\n- 20-40% reduction in lines of code in cluttered files\n- Faster code comprehension for new developers\n- Smaller bundle sizes (tree-shaking works better)\n- Clearer dependency graphs for refactoring tools\n- Eliminates false positives in static analysis\n\n### References\n\n- ESLint: no-unused-vars, no-unused-imports\n- TypeScript: noUnusedLocals, noUnusedParameters\n- Python: F401 (unused import), F841 (unused variable)\n\n### 7.2 Delete Code, Never Comment It Out\n\nCommented-out code is visual noise that raises unanswerable questions: Is this a work in progress? A rollback option? An alternative approach? Code archaeology shows commented blocks are almost never uncommented - they just accumulate. Version control exists specifically to recover old code; use it.\n\n**Incorrect (commented code preserved):**\n\n```javascript\nexport async function fetchUserData(userId) {\n // const cachedUser = cache.get(userId);\n // if (cachedUser) {\n // return cachedUser;\n // }\n\n const response = await api.get(`/users/${userId}`);\n\n // Old implementation - keeping just in case\n // const response = await fetch(`${API_URL}/users/${userId}`, {\n // headers: { 'Authorization': `Bearer ${token}` },\n // cache: 'no-store'\n // });\n // if (!response.ok) {\n // throw new Error(`HTTP ${response.status}`);\n // }\n // const data = await response.json();\n\n // TODO: maybe add this back later?\n // cache.set(userId, response.data, TTL);\n\n return response.data;\n}\n```\n\n**Correct (clean code, history in git):**\n\n```javascript\nexport async function fetchUserData(userId) {\n const response = await api.get(`/users/${userId}`);\n return response.data;\n}\n```\n\n### Recovery Workflow\n\nWhen you need old code back:\n1. `git log --oneline -20` - find the commit\n2. `git show \u003ccommit>:path/to/file` - view the old version\n3. `git checkout \u003ccommit> -- path/to/file` - restore if needed\n\n### When NOT to Apply\n\n- Active debugging session (delete before committing)\n- Code review showing before/after for context (use diff view instead)\n- Documentation explicitly showing what NOT to do\n\n### Benefits\n\n- Files are 10-30% shorter without commented code blocks\n- Clear intent: every line of code has a purpose\n- No confusion about what's active vs inactive\n- git blame shows actual history, not comment archaeology\n- Encourages proper use of version control\n\n### 7.3 Remove Comments That State the Obvious\n\nComments that repeat what the code says add noise without value. They double the reading burden and inevitably drift out of sync with the code they describe. Well-named variables and functions are self-documenting; comments should add context the code cannot express.\n\n**Incorrect (comments repeat the code):**\n\n```typescript\n// Import React\nimport React from 'react';\n\n// User interface\ninterface User {\n id: string; // The user's ID\n name: string; // The user's name\n email: string; // The user's email\n age: number; // The user's age\n}\n\n// Function to get user by ID\nfunction getUserById(id: string): User | null {\n // Find the user in the array\n const user = users.find(u => u.id === id);\n\n // If user is not found, return null\n if (!user) {\n return null;\n }\n\n // Return the user\n return user;\n}\n\n// Increment counter\ncounter++;\n\n// Set loading to true\nsetLoading(true);\n\n// Loop through items\nfor (const item of items) {\n // Process the item\n processItem(item);\n}\n```\n\n**Correct (self-documenting code, no redundant comments):**\n\n```typescript\nimport React from 'react';\n\ninterface User {\n id: string;\n name: string;\n email: string;\n age: number;\n}\n\nfunction getUserById(id: string): User | null {\n return users.find(u => u.id === id) ?? null;\n}\n\ncounter++;\nsetLoading(true);\n\nfor (const item of items) {\n processItem(item);\n}\n```\n\n### What Makes a Comment Obvious?\n\n- Restates the identifier name: `// the user's name` for `userName`\n- Describes the language construct: `// loop through items` for a for loop\n- Explains standard operations: `// return the result`\n- Documents trivial getters/setters with no logic\n\n### When NOT to Apply\n\n- Regex patterns that need explanation\n- Complex algorithms that benefit from step descriptions\n- Non-obvious magic numbers or business rules\n- Workarounds for known bugs or platform quirks\n- Public API documentation (JSDoc, docstrings)\n\n### Benefits\n\n- 30-50% fewer comment lines without information loss\n- Comments that remain are actually valuable\n- Reduces maintenance burden of keeping comments in sync\n- Forces better naming instead of relying on comments\n- Faster code scanning without visual noise\n\n### 7.4 Remove Stale TODO/FIXME Comments\n\nTODO and FIXME comments are promises that rarely get kept. They accumulate over months and years until codebases have hundreds of stale reminders that everyone ignores. Either convert TODOs to tracked issues with owners and deadlines, or delete them. If something matters, it belongs in your issue tracker.\n\n**Incorrect (accumulated stale TODOs):**\n\n```typescript\nexport class UserService {\n // TODO: add caching\n // FIXME: this is slow\n // TODO: refactor this whole class (2019-03-15)\n // HACK: temporary fix for login bug\n // XXX: revisit this later\n\n async getUser(id: string): Promise\u003cUser> {\n // TODO: handle the case where user doesn't exist\n // FIXME: should validate id format\n const user = await this.db.query(`SELECT * FROM users WHERE id = ?`, [id]);\n\n // TODO: add proper error handling\n // TODO: log this somewhere\n // NOTE: Bob said to fix this - not sure what he meant\n return user;\n }\n\n // TODO(john): finish implementing this\n // TODO: write tests\n async updateUser(id: string, data: Partial\u003cUser>): Promise\u003cvoid> {\n // FIXME: SQL injection vulnerability!!!\n await this.db.query(`UPDATE users SET ${data} WHERE id = ${id}`);\n }\n}\n```\n\n**Correct (clean code, issues in tracker):**\n\n```typescript\nexport class UserService {\n async getUser(id: string): Promise\u003cUser | null> {\n const user = await this.db.query(`SELECT * FROM users WHERE id = ?`, [id]);\n return user ?? null;\n }\n\n async updateUser(id: string, data: Partial\u003cUser>): Promise\u003cvoid> {\n // Security: parameterized query prevents SQL injection\n const setClauses = Object.keys(data).map(k => `${k} = ?`).join(', ');\n await this.db.query(\n `UPDATE users SET ${setClauses} WHERE id = ?`,\n [...Object.values(data), id]\n );\n }\n}\n\n// Issue tracker entries created:\n// - PROJ-1234: Add Redis caching layer to UserService\n// - PROJ-1235: Add input validation for user ID format\n// - PROJ-1236: Implement proper error handling in data layer\n```\n\n### TODO Triage Process\n\nWhen you find a TODO, decide:\n1. **Fix it now** - If it takes \u003c 5 minutes, just do it\n2. **Create issue** - If it's real work, track it properly\n3. **Delete it** - If it's vague, stale, or no longer relevant\n\n### Signs a TODO is Stale\n\n- Date older than 6 months\n- Author no longer on team\n- References completed work or old versions\n- Vague (\"make better\", \"fix this\", \"???\")\n- No one knows why it's there\n\n### Benefits\n\n- Issue tracker becomes single source of truth\n- TODO count stays near zero (easy to spot new ones)\n- Urgent FIXMEs don't get lost in noise\n- Code review can focus on real issues\n- New developers don't inherit archaeological debt\n\n### References\n\n- Most IDEs can extract TODOs to tasks: \"TODO to Issue\" extensions\n- CI tools can fail builds on TODO count thresholds\n- `grep -r \"TODO\\|FIXME\" --include=\"*.ts\" | wc -l` for auditing\n\n### 7.5 Keep Comments That Explain Why, Not What\n\nCode shows what happens; only comments can explain why. Keep comments that capture business decisions, workarounds, non-obvious constraints, and historical context. These comments prevent future developers from \"fixing\" intentional behavior or repeating mistakes that led to the current implementation.\n\n**Incorrect (removing valuable context):**\n\n```typescript\n// Before removing comments:\nfunction processPayment(amount: number): boolean {\n // Visa requires amounts in cents, not dollars\n const centAmount = Math.round(amount * 100);\n\n // Retry limit set by PCI compliance audit (see JIRA-4521)\n const maxRetries = 3;\n\n // Must sleep 100ms between retries - payment gateway rate limits\n // Discovered during Black Friday 2023 outage\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n\n// After overzealous cleanup - WRONG:\nfunction processPayment(amount: number): boolean {\n const centAmount = Math.round(amount * 100);\n const maxRetries = 3;\n\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n// Future dev removes sleep(100) as \"unnecessary\" -> outage\n// Future dev changes maxRetries to 10 -> compliance violation\n```\n\n**Correct (preserve why comments):**\n\n```typescript\nfunction processPayment(amount: number): boolean {\n // Visa requires amounts in cents, not dollars\n const centAmount = Math.round(amount * 100);\n\n // Retry limit set by PCI compliance audit (JIRA-4521)\n const maxRetries = 3;\n\n // 100ms delay required by payment gateway rate limits (Black Friday 2023 postmortem)\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n```\n\n**Comments worth keeping:**\n\n```python\n# Business rule: orders over $10k require manual approval (legal requirement)\nif order.total > 10000:\n order.status = \"pending_review\"\n\n# HACK: Safari doesn't support this API before v15, polyfill only for Safari\n# Remove after dropping Safari 14 support (EOL March 2024)\nif is_safari and version \u003c 15:\n load_polyfill()\n\n# WARNING: DO NOT change sort order - downstream systems depend on this\n# exact ordering for invoice reconciliation (see incident #892)\ntransactions.sort(key=lambda t: (t.date, t.id))\n\n# Performance: using raw SQL because ORM generates N+1 queries here\n# Benchmarked: 50ms vs 2.3s for 1000 records\ncursor.execute(RAW_QUERY, params)\n\n# Counterintuitive: we check for empty BEFORE validation because\n# empty arrays are valid (user clearing their cart) but the validator\n# rejects them. Business confirmed this behavior in Q3 product review.\nif not items:\n return Success(empty_cart)\n```\n\n### Categories of Why Comments Worth Keeping\n\n1. **Business rules**: Legal, compliance, contractual requirements\n2. **Workarounds**: Browser bugs, library quirks, API limitations\n3. **Performance**: Why a non-obvious approach was faster\n4. **Historical**: Incidents, postmortems, decisions that led here\n5. **Warnings**: Things that look wrong but are intentional\n\n### Benefits\n\n- Preserves institutional knowledge\n- Prevents regression of intentional behavior\n- Reduces \"why is this here?\" Slack messages\n- Makes code archaeology faster during incidents\n- Protects against well-meaning \"cleanup\" that breaks things\n\n---\n\n## 8. Language Idioms (LOW-MEDIUM)\n\nApply language-specific patterns that improve clarity: TypeScript strict types, Rust ownership, Python comprehensions, Go error handling.\n\n### 8.1 Use Strict Types Over any (TypeScript)\n\nUsing `any` defeats TypeScript's purpose and hides bugs that would otherwise be caught at compile time. Prefer `unknown` with type narrowing when the type is truly uncertain—this forces explicit type checking before use, making your code both safer and more self-documenting.\n\n**Incorrect (using any bypasses type checking):**\n\n```typescript\nfunction processData(data: any) {\n // No type safety - runtime errors possible\n return data.items.map((item: any) => item.name.toUpperCase());\n}\n\nfunction parseResponse(response: any): any {\n return JSON.parse(response.body);\n}\n```\n\n**Correct (using unknown with narrowing):**\n\n```typescript\ninterface DataWithItems {\n items: Array\u003c{ name: string }>;\n}\n\nfunction isDataWithItems(data: unknown): data is DataWithItems {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'items' in data &&\n Array.isArray((data as DataWithItems).items)\n );\n}\n\nfunction processData(data: unknown): string[] {\n if (!isDataWithItems(data)) {\n throw new Error('Invalid data structure');\n }\n return data.items.map(item => item.name.toUpperCase());\n}\n\ninterface ApiResponse {\n body: string;\n}\n\nfunction parseResponse(response: ApiResponse): unknown {\n return JSON.parse(response.body);\n}\n```\n\n### When to Allow any\n\n- Legacy code migration where full typing isn't feasible yet\n- Third-party libraries without type definitions (prefer `@types/*` packages)\n- Explicit `// eslint-disable-next-line @typescript-eslint/no-explicit-any` with justification\n\n### Benefits\n\n- Compiler catches type mismatches before runtime\n- IDE autocomplete works correctly\n- Refactoring becomes safer with full type coverage\n- Self-documenting code through explicit type contracts\n\n### 8.2 Use const Assertions and readonly for Immutability (TypeScript)\n\nConst assertions (`as const`) and `readonly` modifiers signal intent and prevent accidental mutations. They also enable TypeScript to infer literal types instead of widened types, which improves type safety and enables better autocomplete.\n\n**Incorrect (mutable by default, widened types):**\n\n```typescript\n// Type is string[], not readonly [\"admin\", \"user\", \"guest\"]\nconst ROLES = [\"admin\", \"user\", \"guest\"];\n\n// Type is { status: string; code: number }, loses literal info\nconst ERROR_CODES = {\n NOT_FOUND: { status: \"not_found\", code: 404 },\n FORBIDDEN: { status: \"forbidden\", code: 403 },\n};\n\n// Can be accidentally mutated\nfunction processItems(items: string[]) {\n items.push(\"extra\"); // Mutates original array\n return items.sort();\n}\n```\n\n**Correct (immutable with precise types):**\n\n```typescript\n// Type is readonly [\"admin\", \"user\", \"guest\"]\nconst ROLES = [\"admin\", \"user\", \"guest\"] as const;\ntype Role = typeof ROLES[number]; // \"admin\" | \"user\" | \"guest\"\n\n// Type preserves literal values\nconst ERROR_CODES = {\n NOT_FOUND: { status: \"not_found\", code: 404 },\n FORBIDDEN: { status: \"forbidden\", code: 403 },\n} as const;\ntype ErrorStatus = typeof ERROR_CODES[keyof typeof ERROR_CODES][\"status\"];\n\n// Signals no mutation, creates new array\nfunction processItems(items: readonly string[]): string[] {\n return [...items, \"extra\"].sort();\n}\n```\n\n### When NOT to Use\n\n- Arrays or objects that genuinely need mutation for performance\n- Loop counters and accumulator variables\n- Builder patterns that rely on mutation\n\n### Benefits\n\n- Literal type inference enables exhaustive switch checks\n- `readonly` in function parameters documents non-mutation\n- Catches accidental `.push()`, `.pop()`, assignment at compile time\n- Enables deriving union types from const arrays/objects\n\n### 8.3 Use ? for Error Propagation (Rust)\n\nThe `?` operator is Rust's idiomatic way to propagate errors up the call stack. It replaces verbose nested `match` statements with a concise syntax that makes the happy path obvious while still handling errors explicitly. This is central to Rust's philosophy of making error handling visible but not burdensome.\n\n**Incorrect (nested match statements obscure logic):**\n\n```rust\nfn read_config(path: &str) -> Result\u003cConfig, ConfigError> {\n let file = match File::open(path) {\n Ok(f) => f,\n Err(e) => return Err(ConfigError::IoError(e)),\n };\n\n let mut contents = String::new();\n match file.read_to_string(&mut contents) {\n Ok(_) => {},\n Err(e) => return Err(ConfigError::IoError(e)),\n };\n\n match serde_json::from_str(&contents) {\n Ok(config) => Ok(config),\n Err(e) => Err(ConfigError::ParseError(e)),\n }\n}\n```\n\n**Correct (? operator for clean propagation):**\n\n```rust\nfn read_config(path: &str) -> Result\u003cConfig, ConfigError> {\n let mut file = File::open(path)?;\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n let config = serde_json::from_str(&contents)?;\n Ok(config)\n}\n\n// Even cleaner with method chaining\nfn read_config_chained(path: &str) -> Result\u003cConfig, ConfigError> {\n let contents = std::fs::read_to_string(path)?;\n Ok(serde_json::from_str(&contents)?)\n}\n```\n\n### When to Use match Instead\n\n- When you need to handle specific error variants differently\n- When you want to add context or transform the error\n- When recovery is possible and you don't want to propagate\n\n```rust\n// match is appropriate here - different handling per error\nfn connect_with_retry(addr: &str) -> Result\u003cConnection, Error> {\n match TcpStream::connect(addr) {\n Ok(stream) => Ok(Connection::new(stream)),\n Err(e) if e.kind() == ErrorKind::ConnectionRefused => {\n thread::sleep(Duration::from_secs(1));\n connect_with_retry(addr) // Retry on refused\n }\n Err(e) => Err(e.into()), // Propagate other errors\n }\n}\n```\n\n### Benefits\n\n- Happy path is immediately visible\n- Error propagation is explicit but concise\n- Works with both `Result` and `Option` types\n- Combines well with `From` trait for automatic error conversion\n\n### 8.4 Use Iterator Chains When Clearer Than Loops (Rust)\n\nRust's iterator combinators (`map`, `filter`, `fold`, etc.) can express data transformations more declaratively than loops. However, they're not always clearer—complex chains with multiple closures or stateful operations often become harder to understand than equivalent loops. Choose based on readability, not style preference.\n\n**Incorrect (forced iterator chain hurts clarity):**\n\n```rust\n// Too complex - hard to follow the logic\nfn process_orders(orders: &[Order]) -> HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> {\n orders\n .iter()\n .filter(|o| o.status == Status::Pending)\n .filter_map(|o| {\n if let Some(customer) = get_customer(o.customer_id) {\n Some((customer, o))\n } else {\n log::warn!(\"Unknown customer: {}\", o.customer_id);\n None\n }\n })\n .map(|(customer, order)| {\n let processed = process_single_order(order, &customer);\n (customer.id, processed)\n })\n .fold(HashMap::new(), |mut acc, (id, order)| {\n acc.entry(id).or_default().push(order);\n acc\n })\n}\n```\n\n**Correct (loop is clearer for complex logic):**\n\n```rust\nfn process_orders(orders: &[Order]) -> HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> {\n let mut result: HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> = HashMap::new();\n\n for order in orders.iter().filter(|o| o.status == Status::Pending) {\n let Some(customer) = get_customer(order.customer_id) else {\n log::warn!(\"Unknown customer: {}\", order.customer_id);\n continue;\n };\n\n let processed = process_single_order(order, &customer);\n result.entry(customer.id).or_default().push(processed);\n }\n\n result\n}\n```\n\n**Correct (iterator chain for simple transforms):**\n\n```rust\n// Clear and concise - good use of iterators\nfn get_active_user_emails(users: &[User]) -> Vec\u003cString> {\n users\n .iter()\n .filter(|u| u.is_active)\n .map(|u| u.email.clone())\n .collect()\n}\n\n// Sum with filter - straightforward\nfn total_revenue(orders: &[Order]) -> Decimal {\n orders\n .iter()\n .filter(|o| o.status == Status::Completed)\n .map(|o| o.total)\n .sum()\n}\n```\n\n### Guidelines\n\n| Use Iterators When | Use Loops When |\n|-------------------|----------------|\n| Simple filter/map/collect | Multiple related mutations |\n| No side effects needed | Early returns with context |\n| Each step is self-contained | Stateful iteration |\n| 2-3 combinators max | Complex branching logic |\n\n### Benefits of Knowing Both\n\n- Iterator chains can be lazy and more memory-efficient\n- Loops are easier to debug with breakpoints\n- Mixing both (filter in iterator, logic in loop) often optimal\n\n### 8.5 Use Comprehensions for Simple Transforms (Python)\n\nPython comprehensions (list, dict, set, generator) are idiomatic for simple transformations and filtering. They're more concise and often faster than equivalent loops. However, complex comprehensions with multiple conditions or nested logic become unreadable—use regular loops instead.\n\n**Incorrect (loop for simple transform):**\n\n```python\n# Verbose for a simple operation\nresult = []\nfor user in users:\n if user.is_active:\n result.append(user.email)\n\n# Building dict inefficiently\nlookup = {}\nfor item in items:\n lookup[item.id] = item.name\n```\n\n**Correct (comprehension for simple transform):**\n\n```python\n# Clear and Pythonic\nresult = [user.email for user in users if user.is_active]\n\n# Dict comprehension\nlookup = {item.id: item.name for item in items}\n\n# Set comprehension for unique values\nunique_categories = {product.category for product in products}\n\n# Generator for memory efficiency with large data\ntotal = sum(order.amount for order in orders if order.status == \"completed\")\n```\n\n**Incorrect (complex comprehension hurts readability):**\n\n```python\n# Too complex - multiple conditions and transformations\nresult = [\n transform_data(item.value)\n for category in categories\n for item in category.items\n if item.is_valid and item.value > threshold\n if not item.is_deleted\n]\n```\n\n**Correct (loop for complex logic):**\n\n```python\n# Clear with explicit logic\nresult = []\nfor category in categories:\n for item in category.items:\n if not item.is_valid or item.is_deleted:\n continue\n if item.value \u003c= threshold:\n continue\n result.append(transform_data(item.value))\n```\n\n### Guidelines\n\n| Use Comprehensions | Use Loops |\n|-------------------|-----------|\n| Single filter + map | Multiple conditions |\n| One level of nesting | Side effects needed |\n| Fits on one line (~80 chars) | Complex transformations |\n| Pure data transformation | Exception handling required |\n\n### Walrus Operator in Comprehensions (Python 3.8+)\n\n```python\n# Avoid repeated computation\nresults = [y for x in data if (y := expensive_transform(x)) is not None]\n```\n\n### Benefits\n\n- More readable for simple cases\n- Often 10-30% faster than equivalent loops\n- Generator expressions avoid building intermediate lists\n- Clearly signals \"this is a data transformation\"\n\n### 8.6 Handle Errors Immediately After the Call (Go)\n\nGo's explicit error handling is a feature, not a burden. Always check errors immediately after a function call returns—don't defer error checks or accumulate them. This pattern makes control flow explicit and ensures errors are handled in context where you have the most information.\n\n**Incorrect (deferred or accumulated error checking):**\n\n```go\n// Bad: errors accumulate, hard to know which failed\nfunc processFiles(paths []string) error {\n var lastErr error\n\n for _, path := range paths {\n data, err := os.ReadFile(path)\n if err != nil {\n lastErr = err // Previous errors lost\n }\n\n result, err := process(data)\n if err != nil {\n lastErr = err\n }\n\n err = save(result)\n if err != nil {\n lastErr = err\n }\n }\n\n return lastErr\n}\n\n// Bad: ignoring error\nfunc quickRead(path string) []byte {\n data, _ := os.ReadFile(path) // Silent failure\n return data\n}\n```\n\n**Correct (handle immediately with context):**\n\n```go\nfunc processFiles(paths []string) error {\n for _, path := range paths {\n data, err := os.ReadFile(path)\n if err != nil {\n return fmt.Errorf(\"reading %s: %w\", path, err)\n }\n\n result, err := process(data)\n if err != nil {\n return fmt.Errorf(\"processing %s: %w\", path, err)\n }\n\n if err := save(result); err != nil {\n return fmt.Errorf(\"saving result for %s: %w\", path, err)\n }\n }\n\n return nil\n}\n\n// When you need to continue despite errors, collect them explicitly\nfunc processAllFiles(paths []string) error {\n var errs []error\n\n for _, path := range paths {\n if err := processFile(path); err != nil {\n errs = append(errs, fmt.Errorf(\"%s: %w\", path, err))\n continue // Explicit decision to continue\n }\n }\n\n return errors.Join(errs...) // Go 1.20+\n}\n```\n\n### Wrapping Errors for Context\n\n```go\n// Always add context when propagating\nfunc LoadConfig(path string) (*Config, error) {\n data, err := os.ReadFile(path)\n if err != nil {\n return nil, fmt.Errorf(\"load config: %w\", err)\n }\n\n var cfg Config\n if err := json.Unmarshal(data, &cfg); err != nil {\n return nil, fmt.Errorf(\"parse config %s: %w\", path, err)\n }\n\n return &cfg, nil\n}\n```\n\n### When Ignoring Errors is Acceptable\n\n```go\n// Explicitly document why it's safe to ignore\n_ = writer.Close() // Best effort cleanup, already returning another error\n\n// Or use a helper for intentional ignores\nfunc must[T any](v T, err error) T {\n if err != nil {\n panic(err)\n }\n return v\n}\n```\n\n### Benefits\n\n- Errors handled with full context available\n- Control flow is explicit and linear\n- Error wrapping builds informative stack traces\n- No hidden failures or silent data corruption\n\n### 8.7 Prefer Language and Standard Library Builtins\n\nEvery language provides optimized, well-tested utilities for common operations. Manual implementations are almost always buggier, slower, and harder to maintain. Before writing utility code, check if the language or standard library already provides it.\n\n**Incorrect (manual implementations):**\n\n```typescript\n// TypeScript: Manual array operations\nfunction unique\u003cT>(arr: T[]): T[] {\n const seen = new Set\u003cT>();\n const result: T[] = [];\n for (const item of arr) {\n if (!seen.has(item)) {\n seen.add(item);\n result.push(item);\n }\n }\n return result;\n}\n\nfunction groupBy\u003cT>(arr: T[], key: keyof T): Record\u003cstring, T[]> {\n const result: Record\u003cstring, T[]> = {};\n for (const item of arr) {\n const k = String(item[key]);\n if (!result[k]) result[k] = [];\n result[k].push(item);\n }\n return result;\n}\n```\n\n**Correct (use builtins):**\n\n```typescript\n// TypeScript: Use Set and Object.groupBy (ES2024)\nconst uniqueItems = [...new Set(arr)];\nconst grouped = Object.groupBy(arr, item => item.category);\n```\n\n**Incorrect (Python manual operations):**\n\n```python\n# Python: Manual implementations\ndef flatten(nested_list):\n result = []\n for sublist in nested_list:\n for item in sublist:\n result.append(item)\n return result\n\ndef find_max_by_key(items, key_func):\n max_item = None\n max_val = float('-inf')\n for item in items:\n val = key_func(item)\n if val > max_val:\n max_val = val\n max_item = item\n return max_item\n```\n\n**Correct (Python stdlib):**\n\n```python\n# Python: Use itertools and builtins\nfrom itertools import chain\n\nflattened = list(chain.from_iterable(nested_list))\nmax_item = max(items, key=key_func)\n\n# Other commonly overlooked builtins\nfrom collections import Counter, defaultdict\nfrom functools import lru_cache, reduce\nfrom pathlib import Path # Instead of os.path string manipulation\n```\n\n**Incorrect (Go manual operations):**\n\n```go\n// Go: Manual slice operations\nfunc contains(slice []string, item string) bool {\n for _, s := range slice {\n if s == item {\n return true\n }\n }\n return false\n}\n\nfunc min(a, b int) int {\n if a \u003c b {\n return a\n }\n return b\n}\n```\n\n**Correct (Go stdlib and generics):**\n\n```go\n// Go 1.21+: Use slices and cmp packages\nimport (\n \"slices\"\n \"cmp\"\n)\n\nfound := slices.Contains(slice, item)\nminimum := min(a, b) // builtin since Go 1.21\nsorted := slices.SortedFunc(items, func(a, b Item) int {\n return cmp.Compare(a.Priority, b.Priority)\n})\n```\n\n### Common Builtins to Know\n\n| Operation | TypeScript | Python | Go | Rust |\n|-----------|------------|--------|-----|------|\n| Unique | `new Set()` | `set()` | `slices.Compact` | `.dedup()` |\n| Sort | `.sort()` | `sorted()` | `slices.Sort` | `.sort()` |\n| Find | `.find()` | `next(x for...)` | `slices.Index` | `.find()` |\n| Group | `Object.groupBy` | `itertools.groupby` | manual/lo | `.group_by()` |\n| Flatten | `.flat()` | `chain.from_iterable` | manual | `.flatten()` |\n\n### Benefits\n\n- Battle-tested implementations with edge cases handled\n- Often optimized at the language/runtime level\n- Familiar to other developers reading your code\n- Reduces maintenance burden and potential bugs\n\n---\n\n## References\n\n- [Refactoring Catalog](https://refactoring.com/catalog/)\n- [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)\n- [Google Style Guides](https://google.github.io/styleguide/)\n- [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/)\n- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/)\n- [Effective Go](https://go.dev/doc/effective_go)\n- [PEP 8 - Style Guide for Python Code](https://peps.python.org/pep-0008/)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":113363,"content_sha256":"e4e0d634e65acb628836eede20df97247bfcadb02ebacc1d4cd968cb26ab7395"},{"filename":"assets/templates/_template.md","content":"---\ntitle: {Rule Title}\nimpact: {CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW}\nimpactDescription: {Quantified impact, e.g., \"reduces nesting by 40%\", \"prevents 90% of behavior changes\"}\ntags: {prefix}, {technique}, {related-concepts}\n---\n\n## {Rule Title}\n\n{1-3 sentences explaining WHY this matters for code simplification. Focus on maintainability, readability, and behavior preservation.}\n\n**Incorrect ({what's wrong}):**\n\n```{language}\n{Bad code example - production-realistic, not strawman}\n{// Comments explaining the problem}\n```\n\n**Correct ({what's right}):**\n\n```{language}\n{Good code example - minimal diff from incorrect}\n{// Comments explaining the benefit}\n```\n\n{Optional sections as needed:}\n\n**Alternative ({context}):**\n\n```{language}\n{Alternative approach when applicable}\n```\n\n**When NOT to Apply:**\n\n- {Exception 1 - when this rule doesn't apply}\n- {Exception 2 - legitimate reasons to skip this rule}\n\n**Benefits:**\n\n- {Benefit 1 - specific, measurable improvement}\n- {Benefit 2 - additional positive outcome}\n\nReference: [{Reference Title}]({Reference URL})\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1081,"content_sha256":"4723a6785b1c3e4e9ed09fb5fc204a46e0c5e76a86d8bd0f5dfa4a87b69f0072"},{"filename":"metadata.json","content":"{\n \"version\": \"1.0.7\",\n \"organization\": \"Community\",\n \"technology\": \"Code Simplification\",\n \"date\": \"January 2026\",\n \"abstract\": \"Comprehensive code simplification guide for AI agents and LLMs. Contains 45 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.\",\n \"references\": [\n \"https://refactoring.com/catalog/\",\n \"https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882\",\n \"https://google.github.io/styleguide/\",\n \"https://rust-lang.github.io/api-guidelines/\",\n \"https://www.typescriptlang.org/docs/handbook/\",\n \"https://go.dev/doc/effective_go\",\n \"https://peps.python.org/pep-0008/\"\n ]\n}\n","content_type":"application/json; charset=utf-8","language":"json","size":922,"content_sha256":"e415d38dd3abaa273a0412a1b6f70c6a50c4984b59d81c0a8fe7d0f0272ca59e"},{"filename":"README.md","content":"# Code Simplifier Skill\n\nA comprehensive code simplification skill for AI agents and LLMs, containing 45 rules across 8 categories.\n\n## Overview\n\nThis skill guides code simplification with a focus on:\n- **Context-first approach**: Understand project conventions before making changes\n- **Behavior preservation**: Change how code is written, never what it does\n- **Scope discipline**: Focus on recently modified code, keep diffs small\n- **Clarity over brevity**: Explicit, readable code beats clever one-liners\n\n## Structure\n\n```\ncode-simplifier/\n├── SKILL.md # Entry point with quick reference\n├── README.md # This file\n├── metadata.json # Version, organization, references\n├── references/\n│ ├── _sections.md # Category definitions and ordering\n│ ├── ctx-*.md # Context Discovery rules (5)\n│ ├── behave-*.md # Behavior Preservation rules (6)\n│ ├── scope-*.md # Scope Management rules (5)\n│ ├── flow-*.md # Control Flow rules (7)\n│ ├── name-*.md # Naming and Clarity rules (5)\n│ ├── dup-*.md # Duplication Reduction rules (5)\n│ ├── dead-*.md # Dead Code Elimination rules (5)\n│ └── idiom-*.md # Language Idioms rules (7)\n└── assets/\n └── templates/\n └── _template.md # Template for new rules\n```\n\n## Getting Started\n\n```bash\n# No installation required - this is a documentation-only skill\n# For development/validation:\npnpm install # Install validation dependencies (optional)\npnpm build # Build/compile AGENTS.md from source rules\npnpm validate # Validate skill structure and content\n```\n\n1. Read `SKILL.md` for an overview and quick reference\n2. Check `references/_sections.md` to understand category priorities\n3. Reference individual rules as needed during code simplification tasks\n\n## Creating a New Rule\n\n1. Copy `assets/templates/_template.md` to `references/{prefix}-{slug}.md`\n2. Fill in frontmatter: title, impact, impactDescription, tags\n3. Write WHY explanation (1-3 sentences)\n4. Add incorrect and correct code examples\n5. Update `SKILL.md` quick reference section\n\n## Rule File Structure\n\nEach rule file follows this format:\n\n```markdown\n---\ntitle: Rule Title\nimpact: CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW\nimpactDescription: Quantified impact (e.g., \"reduces nesting by 40%\")\ntags: prefix, technique, related-concepts\n---\n\n## Rule Title\n\nWHY this matters (1-3 sentences).\n\n**Incorrect (what's wrong):**\n\\`\\`\\`language\nBad example\n\\`\\`\\`\n\n**Correct (what's right):**\n\\`\\`\\`language\nGood example - minimal diff from incorrect\n\\`\\`\\`\n```\n\n## File Naming Convention\n\n- Prefix must match category: `ctx-`, `behave-`, `scope-`, `flow-`, `name-`, `dup-`, `dead-`, `idiom-`\n- Slug should be descriptive: `early-return`, `preserve-outputs`, `rule-of-three`\n- Examples: `flow-early-return.md`, `behave-preserve-api.md`, `dup-rule-of-three.md`\n\n## Impact Levels\n\n| Level | Description | When to Use |\n|-------|-------------|-------------|\n| CRITICAL | Must follow, violations cause bugs or breaking changes | Context discovery, behavior preservation |\n| HIGH | Strongly recommended, violations harm maintainability | Scope management, control flow |\n| MEDIUM-HIGH | Recommended for clarity and consistency | Naming conventions |\n| MEDIUM | Good practice, apply when beneficial | Duplication, dead code |\n| LOW-MEDIUM | Nice to have, language-specific optimizations | Language idioms |\n\n## Scripts\n\nValidate the skill structure and content:\n\n```bash\nnode ~/.claude/plugins/cache/dot-claude/dev-skill/*/scripts/validate-skill.js ./code-simplifier\n```\n\n## Contributing\n\n1. Follow the rule template exactly\n2. Ensure the first tag matches the file prefix\n3. Use production-realistic code examples (no foo/bar/baz)\n4. Quantify impact where possible\n5. Include \"When NOT to Apply\" section for complex rules\n6. Run validation before submitting\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4078,"content_sha256":"99db9603b57cf056541af7763bd2b875ef8d9d4121a21f2d247fbeb61a1ec169"},{"filename":"references/_sections.md","content":"# Sections\n\nThis file defines all sections, their ordering, impact levels, and descriptions.\nThe section ID (in parentheses) is the filename prefix used to group rules.\n\n---\n\n## 1. Context Discovery (ctx)\n\n**Impact:** CRITICAL\n**Description:** Before making any changes, understand project conventions by reading CLAUDE.md, linting configs, and existing patterns. Project standards override generic guidance. Scoping to recently modified code is covered in the Scope Management section.\n\n## 2. Behavior Preservation (behave)\n\n**Impact:** CRITICAL\n**Description:** Simplification must never change what code does - only how it is written. Outputs, error handling, side effects, and API surfaces must remain identical.\n\n## 3. Scope Management (scope)\n\n**Impact:** HIGH\n**Description:** Focus on recently modified code only. Keep diffs small and reviewable. Avoid unrelated refactors, global rewrites, or architectural changes.\n\n## 4. Control Flow Simplification (flow)\n\n**Impact:** HIGH\n**Description:** Reduce nesting through early returns and guard clauses. Avoid nested ternaries. Prefer explicit control flow over dense expressions.\n\n## 5. Naming and Clarity (name)\n\n**Impact:** MEDIUM-HIGH\n**Description:** Use precise, intention-revealing names. Nouns for data, verbs for actions. Descriptive names over implicit abbreviations.\n\n## 6. Duplication Reduction (dup)\n\n**Impact:** MEDIUM\n**Description:** Extract helpers when code appears 3+ times and extraction improves clarity. Avoid single-use abstractions that obscure intent.\n\n## 7. Dead Code Elimination (dead)\n\n**Impact:** MEDIUM\n**Description:** Remove unused code, redundant comments, and obsolete patterns. Delete rather than comment out. Keep comments that explain \"why\" not \"what\".\n\n## 8. Language Idioms (idiom)\n\n**Impact:** LOW-MEDIUM\n**Description:** Apply language-specific patterns that improve clarity: TypeScript strict types, Rust ownership, Python comprehensions, Go error handling.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1954,"content_sha256":"f9fb5c7e74e42b49afdd789262233bb46d561e32a4f797acd2044a1d55c81623"},{"filename":"references/behave-no-semantics-change.md","content":"---\ntitle: Forbid Subtle Semantic Changes\nimpact: CRITICAL\nimpactDescription: Semantic changes like null vs undefined or == vs === cause bugs that pass 95% of tests but fail in edge cases only discovered in production\ntags: behave, semantics, null, undefined, equality, coercion\n---\n\n## Forbid Subtle Semantic Changes\n\nThe most dangerous simplifications are those that look equivalent but have different semantics. Null vs undefined, loose vs strict equality, truthy vs explicit checks - these distinctions matter. Code that appears cleaner may silently change behavior for edge cases that existing tests do not cover.\n\n**Incorrect (changes null/undefined semantics):**\n\n```typescript\n// Before: explicitly checks for null\nfunction getDisplayName(user: User | null): string {\n if (user === null) {\n return 'Anonymous';\n }\n return user.name;\n}\n\n// After \"simplification\": truthy check\nfunction getDisplayName(user: User | null): string {\n return user ? user.name : 'Anonymous';\n}\n// Breaks: user with name = '' or name = 0 (if polymorphic)\n```\n\n**Correct (preserve explicit null check):**\n\n```typescript\nfunction getDisplayName(user: User | null): string {\n return user === null ? 'Anonymous' : user.name;\n}\n```\n\n**Incorrect (changes equality semantics):**\n\n```javascript\n// Before: intentional loose equality for null/undefined\nfunction isEmpty(value) {\n return value == null; // Catches both null and undefined\n}\n\n// After \"simplification\": strict equality\nfunction isEmpty(value) {\n return value === null;\n}\n// Breaks: isEmpty(undefined) now returns false\n```\n\n**Correct (preserve loose equality when intentional):**\n\n```javascript\nfunction isEmpty(value) {\n return value == null; // Intentionally catches null and undefined\n}\n```\n\n**Incorrect (changes short-circuit semantics):**\n\n```python\n# Before: returns 0 if items is empty list\ndef first_or_zero(items):\n return items[0] if items else 0\n\n# After \"simplification\": uses or\ndef first_or_zero(items):\n return (items and items[0]) or 0\n# Breaks: returns 0 when items[0] is 0, empty string, False, etc.\n```\n\n**Correct (preserve original semantics):**\n\n```python\ndef first_or_zero(items):\n return items[0] if items else 0\n```\n\n**Incorrect (changes nil vs empty slice semantics):**\n\n```go\n// Before: returns nil when no results found\nfunc findUsers(query string) []User {\n rows := db.Query(query)\n if len(rows) == 0 {\n return nil\n }\n return rows\n}\n\n// After \"simplification\": always returns initialized slice\nfunc findUsers(query string) []User {\n results := make([]User, 0)\n rows := db.Query(query)\n results = append(results, rows...)\n return results\n}\n// Breaks: if findUsers(\"inactive\") == nil { showEmptyState() }\n// json.Marshal(nil slice) = \"null\", json.Marshal(empty slice) = \"[]\"\n```\n\n### When NOT to Apply\n\n- When fixing a bug caused by incorrect semantics\n- When the semantic difference is explicitly documented and approved\n- When migrating to stricter types with full test coverage\n\n### Benefits\n\n- Edge cases continue working correctly\n- No silent failures in production\n- Behavior matches developer expectations\n- Tests remain valid without modification\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3171,"content_sha256":"aec7004d2714777747544056a73234516ff5e17808ff394e5837985043847839"},{"filename":"references/behave-preserve-api.md","content":"---\ntitle: Preserve Public Function Signatures and Types\nimpact: CRITICAL\nimpactDescription: API changes break 100% of callers and require coordinated updates across 5-50+ dependent modules\ntags: behave, api, signatures, types, compatibility\n---\n\n## Preserve Public Function Signatures and Types\n\nPublic APIs are contracts with consumers. Changing parameter order, making required params optional, narrowing accepted types, or modifying return types breaks every caller. Internal simplification must never leak into public interfaces.\n\n**Incorrect (changes parameter order):**\n\n```typescript\n// Before: well-established API\nfunction formatDate(date: Date, format: string, locale?: string): string {\n // ...\n}\n\n// After \"simplification\": reordered for \"consistency\"\nfunction formatDate(format: string, date: Date, locale?: string): string {\n // ...\n}\n// Breaks: formatDate(new Date(), 'YYYY-MM-DD')\n```\n\n**Correct (preserve original signature, simplify internals):**\n\n```typescript\nfunction formatDate(date: Date, format: string, locale?: string): string {\n const loc = locale ?? 'en-US';\n return new Intl.DateTimeFormat(loc, parseFormat(format)).format(date);\n}\n```\n\n**Incorrect (narrows accepted types):**\n\n```python\n# Before: accepts any iterable\ndef process_items(items: Iterable[str]) -> list[str]:\n return [transform(item) for item in items]\n\n# After \"simplification\": requires list\ndef process_items(items: list[str]) -> list[str]:\n return [transform(item) for item in items]\n# Breaks: process_items(generator_expression)\n```\n\n**Correct (preserves type flexibility):**\n\n```python\ndef process_items(items: Iterable[str]) -> list[str]:\n return [transform(item) for item in items]\n```\n\n**Incorrect (makes required parameter optional):**\n\n```go\n// Before: explicit required config\nfunc NewClient(config Config) *Client {\n return &Client{config: config}\n}\n\n// After \"simplification\": optional with default\nfunc NewClient(config ...Config) *Client {\n cfg := Config{}\n if len(config) > 0 {\n cfg = config[0]\n }\n return &Client{config: cfg}\n}\n// Breaks: compile-time safety, caller may forget config\n```\n\n**Correct (preserve required parameter):**\n\n```go\nfunc NewClient(config Config) *Client {\n return &Client{config: config}\n}\n```\n\n### Benefits\n\n- All existing callers continue working\n- No breaking changes in library versions\n- Type safety maintained for consumers\n- Documentation remains accurate\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2437,"content_sha256":"6a702613b26b26c9c7d230d2b5a418072393b045bd734cc80a8f7bf9c4d48151"},{"filename":"references/behave-preserve-errors.md","content":"---\ntitle: Preserve Error Messages, Types, and Handling\nimpact: CRITICAL\nimpactDescription: Changed error types or messages break 100% of catch blocks matching on them, plus monitoring alert rules\ntags: behave, errors, exceptions, error-handling\n---\n\n## Preserve Error Messages, Types, and Handling\n\nError behavior is part of your API contract. Changing exception types, error messages, or when errors are thrown breaks catch blocks, monitoring systems, and user expectations. Simplify error handling code only when the observable error behavior remains identical.\n\n**Incorrect (changes exception type):**\n\n```typescript\n// Before: throws specific error type\nfunction parseConfig(json: string): Config {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new ConfigParseError(`Invalid config: ${e.message}`);\n }\n}\n\n// After \"simplification\": throws generic error\nfunction parseConfig(json: string): Config {\n return JSON.parse(json); // Now throws SyntaxError instead\n}\n// Breaks: catch (e) { if (e instanceof ConfigParseError) ... }\n```\n\n**Correct (preserves error type and message format):**\n\n```typescript\nfunction parseConfig(json: string): Config {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new ConfigParseError(`Invalid config: ${(e as Error).message}`);\n }\n}\n```\n\n**Incorrect (changes error message):**\n\n```python\n# Before: specific error message\ndef validate_age(age: int) -> None:\n if age \u003c 0:\n raise ValueError(\"Age cannot be negative\")\n if age > 150:\n raise ValueError(\"Age cannot exceed 150\")\n\n# After \"simplification\": combined validation\ndef validate_age(age: int) -> None:\n if not 0 \u003c= age \u003c= 150:\n raise ValueError(\"Invalid age\") # Different message!\n# Breaks: tests checking for specific error messages\n```\n\n**Correct (preserves original error messages):**\n\n```python\ndef validate_age(age: int) -> None:\n if age \u003c 0:\n raise ValueError(\"Age cannot be negative\")\n if age > 150:\n raise ValueError(\"Age cannot exceed 150\")\n```\n\n### When NOT to Apply\n\n- When explicitly tasked with improving error messages\n- When error messages contain sensitive information that should be removed\n- When consolidating truly duplicate error paths (same message, same type)\n\n### Benefits\n\n- Catch blocks continue working correctly\n- Monitoring and alerting rules remain valid\n- User-facing error messages stay consistent\n- Error documentation stays accurate\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2440,"content_sha256":"5dd3410a9ad1673be57ae476c2a060fc1314cf39edc17eef222f958cfa701929"},{"filename":"references/behave-preserve-outputs.md","content":"---\ntitle: Preserve All Return Values and Outputs\nimpact: CRITICAL\nimpactDescription: Changed return types (e.g., null vs undefined) cause cascading failures in 100% of dependent code checking strict equality\ntags: behave, outputs, return-values, testing\n---\n\n## Preserve All Return Values and Outputs\n\nCode simplification must never alter what a function returns. Even \"equivalent\" values like empty array vs null, or reordered object keys, can break downstream consumers. Every output - return values, yielded items, emitted events - must remain byte-for-byte identical.\n\n**Incorrect (changes return type from null to undefined):**\n\n```typescript\n// Before: returns null for missing users\nfunction findUser(id: string): User | null {\n const user = users.find(u => u.id === id);\n if (!user) {\n return null;\n }\n return user;\n}\n\n// After \"simplification\": now returns undefined\nfunction findUser(id: string): User | undefined {\n return users.find(u => u.id === id);\n}\n// Breaks: if (findUser(id) === null) { ... }\n```\n\n**Correct (preserves null return type):**\n\n```typescript\nfunction findUser(id: string): User | null {\n return users.find(u => u.id === id) ?? null;\n}\n```\n\n**Incorrect (changes output ordering):**\n\n```python\n# Before: returns sorted by insertion order\ndef get_config():\n return {\"host\": \"localhost\", \"port\": 8080, \"debug\": True}\n\n# After \"simplification\": alphabetical order\ndef get_config():\n return dict(sorted({\"debug\": True, \"host\": \"localhost\", \"port\": 8080}.items()))\n# Breaks: code that relies on iteration order or serialization\n```\n\n**Correct (preserves original ordering):**\n\n```python\ndef get_config():\n return {\"host\": \"localhost\", \"port\": 8080, \"debug\": True}\n```\n\n### Benefits\n\n- Downstream code continues working without modification\n- Tests remain valid without updates\n- API contracts stay honored\n- Serialized outputs remain compatible\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1889,"content_sha256":"8004c802dbec59fd35c4d15fd576582dc654f19dad1b2532573131cbcf4730be"},{"filename":"references/behave-preserve-side-effects.md","content":"---\ntitle: Preserve Side Effects (Logging, I/O, State Changes)\nimpact: CRITICAL\nimpactDescription: Removed logging eliminates 100% of audit trail for that operation; reordered I/O causes data corruption in 10-30% of concurrent scenarios\ntags: behave, side-effects, logging, io, state\n---\n\n## Preserve Side Effects (Logging, I/O, State Changes)\n\nSide effects are often the most important part of a function. Logging enables debugging and auditing. I/O operations persist data. State mutations coordinate systems. Removing or reordering side effects during simplification can cause silent failures that only surface in production.\n\n**Incorrect (removes logging side effect):**\n\n```typescript\n// Before: logs for audit trail\nasync function transferFunds(from: Account, to: Account, amount: number) {\n logger.info(`Transfer initiated: ${from.id} -> ${to.id}, amount: ${amount}`);\n await from.debit(amount);\n await to.credit(amount);\n logger.info(`Transfer completed: ${from.id} -> ${to.id}`);\n}\n\n// After \"simplification\": removed \"noisy\" logging\nasync function transferFunds(from: Account, to: Account, amount: number) {\n await from.debit(amount);\n await to.credit(amount);\n}\n// Breaks: audit compliance, debugging capability\n```\n\n**Correct (preserve all logging):**\n\n```typescript\nasync function transferFunds(from: Account, to: Account, amount: number) {\n logger.info(`Transfer initiated: ${from.id} -> ${to.id}, amount: ${amount}`);\n await from.debit(amount);\n await to.credit(amount);\n logger.info(`Transfer completed: ${from.id} -> ${to.id}`);\n}\n```\n\n**Incorrect (changes I/O timing):**\n\n```python\n# Before: writes happen in sequence\ndef save_order(order: Order) -> None:\n db.save(order)\n cache.invalidate(f\"order:{order.id}\")\n search_index.update(order)\n\n# After \"simplification\": parallel writes\nasync def save_order(order: Order) -> None:\n await asyncio.gather(\n db.save(order),\n cache.invalidate(f\"order:{order.id}\"),\n search_index.update(order)\n )\n# Breaks: cache invalidation may happen before db.save completes\n```\n\n**Correct (preserve operation order):**\n\n```python\ndef save_order(order: Order) -> None:\n db.save(order)\n cache.invalidate(f\"order:{order.id}\")\n search_index.update(order)\n```\n\n**Incorrect (changes state mutation order):**\n\n```go\n// Before: specific mutation order\nfunc (s *Server) Shutdown() {\n s.mu.Lock()\n s.accepting = false\n s.mu.Unlock()\n s.drainConnections()\n s.closeListeners()\n}\n\n// After \"simplification\": reordered\nfunc (s *Server) Shutdown() {\n s.closeListeners() // Moved up\n s.mu.Lock()\n s.accepting = false\n s.mu.Unlock()\n s.drainConnections()\n}\n// Breaks: new connections may be accepted after listeners closed\n```\n\n**Correct (preserve mutation order):**\n\n```go\nfunc (s *Server) Shutdown() {\n s.mu.Lock()\n s.accepting = false\n s.mu.Unlock()\n s.drainConnections()\n s.closeListeners()\n}\n```\n\n### Benefits\n\n- Debugging and monitoring capabilities preserved\n- Data consistency maintained\n- Race conditions avoided\n- Audit trails remain intact\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3081,"content_sha256":"56b05c8b527b2bb25f2c53e01649487b4d84b99737123f6bbba94e7f4162ab9d"},{"filename":"references/behave-verify-before-commit.md","content":"---\ntitle: Verify Behavior Preservation Before Finalizing Changes\nimpact: CRITICAL\nimpactDescription: Unverified simplifications ship bugs to production; verification catches 90% of behavior changes before merge\ntags: behave, verification, testing, review, diff\n---\n\n## Verify Behavior Preservation Before Finalizing Changes\n\nNever assume a simplification preserves behavior - verify it. Run existing tests, manually test edge cases, and review diffs for semantic changes. The confidence that code \"looks equivalent\" is insufficient. Verification must be explicit and documented.\n\n**Incorrect (commits without verification):**\n\n```typescript\n// Developer thinks: \"This is obviously the same\"\n// Before\nfunction isValid(x: number): boolean {\n if (x > 0) {\n if (x \u003c 100) {\n return true;\n }\n }\n return false;\n}\n\n// After \"simplification\" - commits directly\nfunction isValid(x: number): boolean {\n return x > 0 && x \u003c 100;\n}\n// Forgot to run tests, missed that NaN handling differs\n```\n\n**Correct (verifies before committing):**\n\n```typescript\n// 1. Run existing tests first\n// $ npm test -- --grep \"isValid\"\n\n// 2. Check edge cases manually\nconsole.log(isValid(NaN)); // Before: false, After: false ✓\nconsole.log(isValid(0)); // Before: false, After: false ✓\nconsole.log(isValid(100)); // Before: false, After: false ✓\nconsole.log(isValid(50)); // Before: true, After: true ✓\n\n// 3. Review diff for semantic changes\n// git diff --word-diff\n\n// 4. Then commit with verification note\nfunction isValid(x: number): boolean {\n return x > 0 && x \u003c 100;\n}\n```\n\n### Verification Checklist\n\nBefore finalizing any simplification:\n\n1. **Run existing tests** - All tests must pass without modification\n2. **Check edge cases** - null, undefined, empty, zero, negative, boundary values\n3. **Review error paths** - Exceptions, error messages, failure modes\n4. **Verify side effects** - Logging, I/O, state changes still occur\n5. **Test with real data** - If available, run against production-like inputs\n6. **Review the diff** - Look for type changes, reordering, removed code\n\n### Verification Commands by Language\n\n```bash\n# TypeScript/JavaScript\nnpm test\nnpx tsc --noEmit\n\n# Python\npytest\nmypy .\n\n# Go\ngo test ./...\ngo vet ./...\n\n# Rust\ncargo test\ncargo clippy\n```\n\n### When Tests Are Insufficient\n\nIf existing tests do not cover the modified code:\n\n1. **Add tests before simplifying** - Write tests that capture current behavior\n2. **Use snapshot testing** - Capture outputs before and after\n3. **Property-based testing** - Generate inputs to find edge cases\n4. **Manual verification** - Document what was manually checked\n\n### Benefits\n\n- Catches behavior changes before they reach production\n- Builds confidence in simplifications\n- Documents verification for reviewers\n- Creates a safety net for future changes\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2845,"content_sha256":"19d698001b9b7a6c756bf1377d27f9e25f7ad595f4bb4ecbd1bec4828977a1dd"},{"filename":"references/ctx-detect-lint-config.md","content":"---\ntitle: Check for Linting and Formatting Configs\nimpact: CRITICAL\nimpactDescription: Eliminates 100% of style-related CI failures from simplification changes\ntags: ctx, linting, formatting, tooling\n---\n\n## Check for Linting and Formatting Configs\n\nLinting and formatting tools enforce project-wide code standards automatically. Simplifications that ignore these configs will fail CI checks or introduce inconsistent formatting. Always detect and respect ESLint, Prettier, rustfmt, Biome, and similar tool configurations before making changes.\n\n**Incorrect (ignoring project's Prettier config):**\n\n```javascript\n// Simplified code uses single quotes, but project's .prettierrc specifies double quotes\nconst message = 'Hello, world';\nconst items = ['one', 'two', 'three'];\n\nfunction greet(name) {\n return 'Hello, ' + name;\n}\n```\n\n**Correct (matching project's Prettier config with double quotes):**\n\n```javascript\n// .prettierrc: { \"singleQuote\": false }\nconst message = \"Hello, world\";\nconst items = [\"one\", \"two\", \"three\"];\n\nfunction greet(name) {\n return \"Hello, \" + name;\n}\n```\n\n**Config files to check:**\n\n- JavaScript/TypeScript: `.eslintrc.*`, `.prettierrc.*`, `biome.json`, `.editorconfig`\n- Rust: `rustfmt.toml`, `.rustfmt.toml`\n- Python: `pyproject.toml`, `.flake8`, `.black`, `ruff.toml`\n- Go: `.golangci.yml`\n\n**Benefits:**\n\n- CI passes on first push\n- Code matches existing project formatting\n- No manual reformatting required after review\n\n**References:**\n\n- Run `npm run lint` or equivalent before committing\n- Use editor integrations to auto-format on save\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1576,"content_sha256":"4a8503826d671612eb2f456613ed96f0bc06f40c42a0cea79d169806dff14633"},{"filename":"references/ctx-follow-existing-patterns.md","content":"---\ntitle: Match Existing Code Style in File and Project\nimpact: CRITICAL\nimpactDescription: Reduces code review friction by 80% through consistent patterns\ntags: ctx, consistency, patterns, style\n---\n\n## Match Existing Code Style in File and Project\n\nEvery codebase develops its own idioms and patterns over time. Simplifications that introduce foreign patterns, even if technically better, create jarring inconsistencies. Before simplifying, study the surrounding code to understand naming conventions, error handling approaches, and structural patterns already in use.\n\n**Incorrect (introducing arrow functions in a file using function declarations):**\n\n```javascript\n// Existing file uses function declarations throughout\nfunction validateEmail(email) {\n return email.includes(\"@\");\n}\n\nfunction validatePhone(phone) {\n return phone.length === 10;\n}\n\n// New simplified code introduces arrow functions\nconst validateName = (name) => name.length > 0;\n\nconst validateAge = (age) => age >= 0 && age \u003c= 150;\n```\n\n**Correct (matching existing function declaration pattern):**\n\n```javascript\n// Existing file uses function declarations throughout\nfunction validateEmail(email) {\n return email.includes(\"@\");\n}\n\nfunction validatePhone(phone) {\n return phone.length === 10;\n}\n\n// Simplified code follows existing pattern\nfunction validateName(name) {\n return name.length > 0;\n}\n\nfunction validateAge(age) {\n return age >= 0 && age \u003c= 150;\n}\n```\n\n**Patterns to observe:**\n\n- Function declaration style (arrow vs function keyword)\n- Naming conventions (camelCase, snake_case, prefixes)\n- Import organization and grouping\n- Error handling approach (try/catch, Result types, error callbacks)\n- Comment style and documentation format\n\n**When NOT to use:**\n\n- When explicitly refactoring to modernize the entire file\n- When existing patterns are acknowledged anti-patterns by the team\n\n**Benefits:**\n\n- Code reads as if written by one author\n- Easier to maintain and understand\n- Reduces cognitive load during code review\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2016,"content_sha256":"c8e152b0d62ea8adc7590c148976900de14d1b4d4919866f1953c115e4e3e329"},{"filename":"references/ctx-project-over-generic.md","content":"---\ntitle: Project Conventions Override Generic Best Practices\nimpact: CRITICAL\nimpactDescription: Prevents 95% of \"but the best practice says...\" debates in code review\ntags: ctx, conventions, best-practices, pragmatism\n---\n\n## Project Conventions Override Generic Best Practices\n\nGeneric best practices are starting points, not absolute rules. Teams adopt specific conventions for good reasons: domain requirements, performance constraints, team preferences, or historical decisions. When project conventions conflict with generic guidance, always follow the project's established approach.\n\n**Incorrect (applying generic \"arrow function\" pattern against project convention):**\n\n```javascript\n// Project convention: use function declarations for top-level functions\n// Developer applies generic \"arrow functions are cleaner\" simplification\n\n// Existing file uses function declarations throughout\nfunction validateEmail(email) {\n return email.includes(\"@\");\n}\n\n// Developer \"simplifies\" new additions to arrow functions\nconst validatePhone = (phone) => /^\\d{10}$/.test(phone);\nconst validateAge = (age) => age >= 0 && age \u003c= 150;\n```\n\n**Correct (following project's function declaration convention):**\n\n```javascript\n// Project convention documented: \"Use function declarations for all named functions\"\n// This team prefers hoisting behavior and consistent style\n\nfunction validateEmail(email) {\n return email.includes(\"@\");\n}\n\nfunction validatePhone(phone) {\n return /^\\d{10}$/.test(phone);\n}\n\nfunction validateAge(age) {\n return age >= 0 && age \u003c= 150;\n}\n```\n\n**Common conflicts:**\n\n- Early returns vs explicit else blocks\n- Inline conditionals vs extracted functions\n- ORM usage vs raw SQL (some teams mandate one)\n- Dependency injection style\n- Test naming conventions\n\n**When to propose changes to conventions:**\n\n- Open a discussion with the team first\n- Document the reasoning for the change\n- Apply consistently across the codebase, not piecemeal\n\n**Benefits:**\n\n- Respects team decisions and domain knowledge\n- Avoids religious debates about style\n- Simplifications are accepted without friction\n\n**References:**\n\n- Check team wikis, ADRs (Architecture Decision Records)\n- Ask maintainers when conventions seem unusual\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2233,"content_sha256":"7a57bc614394ab0f1dc51541f1e4542d0f325620949766d8d8feafbb9a6f3976"},{"filename":"references/ctx-read-claude-md.md","content":"---\ntitle: Always Read CLAUDE.md Before Simplifying\nimpact: CRITICAL\nimpactDescription: Prevents 90% of rejected PRs due to violating undocumented project conventions\ntags: ctx, conventions, project-setup\n---\n\n## Always Read CLAUDE.md Before Simplifying\n\nProject-specific instructions in CLAUDE.md define how code should be written, tested, and structured. Ignoring these instructions leads to simplifications that violate project standards, causing rework and rejected changes. Reading CLAUDE.md first ensures your simplifications align with the team's established practices.\n\n**Incorrect (simplifying without reading project instructions):**\n\n```typescript\n// Developer simplifies by removing \"unnecessary\" error handling\n// Not knowing CLAUDE.md requires explicit error boundaries\nfunction fetchUser(id: string) {\n return api.get(`/users/${id}`);\n}\n```\n\n**Correct (reading CLAUDE.md first, respecting error handling requirement):**\n\n```typescript\n// CLAUDE.md specifies: \"All API calls must have explicit error handling\"\nfunction fetchUser(id: string) {\n try {\n return api.get(`/users/${id}`);\n } catch (error) {\n throw new UserFetchError(id, error);\n }\n}\n```\n\n**When NOT to use:**\n\n- When CLAUDE.md does not exist in the project\n- For exploratory analysis where no changes will be made\n\n**Benefits:**\n\n- Simplifications are accepted on first review\n- Maintains consistency with team expectations\n- Avoids introducing patterns the team has explicitly rejected\n\n**References:**\n\n- Check `.claude/CLAUDE.md`, `CLAUDE.md`, and parent directory CLAUDE.md files\n- Look for `AGENTS.md` or similar instruction files\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1622,"content_sha256":"81592824f47a65c075859d197a02c7baf640d000721269a017c15e2763d42cd7"},{"filename":"references/dead-delete-not-comment.md","content":"---\ntitle: Delete Code, Never Comment It Out\nimpact: MEDIUM\nimpactDescription: Commented code creates confusion about intent, bloats files by 10-30%, and is never actually restored from comments\ntags: dead, comments, version-control, git, cleanup\n---\n\n## Delete Code, Never Comment It Out\n\nCommented-out code is visual noise that raises unanswerable questions: Is this a work in progress? A rollback option? An alternative approach? Code archaeology shows commented blocks are almost never uncommented - they just accumulate. Version control exists specifically to recover old code; use it.\n\n**Incorrect (commented code preserved):**\n\n```javascript\nexport async function fetchUserData(userId) {\n // const cachedUser = cache.get(userId);\n // if (cachedUser) {\n // return cachedUser;\n // }\n\n const response = await api.get(`/users/${userId}`);\n\n // Old implementation - keeping just in case\n // const response = await fetch(`${API_URL}/users/${userId}`, {\n // headers: { 'Authorization': `Bearer ${token}` },\n // cache: 'no-store'\n // });\n // if (!response.ok) {\n // throw new Error(`HTTP ${response.status}`);\n // }\n // const data = await response.json();\n\n // TODO: add caching back when Redis is configured\n // cache.set(userId, response.data, TTL);\n\n return response.data;\n}\n```\n\n**Correct (clean code, history in git):**\n\n```javascript\nexport async function fetchUserData(userId) {\n const response = await api.get(`/users/${userId}`);\n return response.data;\n}\n```\n\n**Incorrect (multiple commented alternatives):**\n\n```python\nclass OrderProcessor:\n def calculate_tax(self, order):\n # V1: Simple percentage\n # return order.subtotal * 0.08\n\n # V2: State-based tax\n # tax_rate = TAX_RATES.get(order.state, 0.0)\n # return order.subtotal * tax_rate\n\n # V3: External tax service (current)\n return self.tax_service.calculate(order)\n\n # V4: Planned - tax by item category\n # total_tax = 0\n # for item in order.items:\n # rate = CATEGORY_RATES.get(item.category, DEFAULT_RATE)\n # total_tax += item.price * rate\n # return total_tax\n```\n\n**Correct (single implementation, alternatives in git history or issues):**\n\n```python\nclass OrderProcessor:\n def calculate_tax(self, order):\n return self.tax_service.calculate(order)\n```\n\n**Incorrect (debug code commented):**\n\n```go\nfunc ProcessBatch(items []Item) error {\n // fmt.Printf(\"DEBUG: Processing %d items\\n\", len(items))\n\n for i, item := range items {\n // fmt.Printf(\"DEBUG: Item %d: %+v\\n\", i, item)\n if err := process(item); err != nil {\n // fmt.Printf(\"DEBUG: Error at %d: %v\\n\", i, err)\n return fmt.Errorf(\"item %d: %w\", i, err)\n }\n }\n\n // fmt.Println(\"DEBUG: Batch complete\")\n return nil\n}\n```\n\n**Correct (use proper logging or delete debug code):**\n\n```go\nfunc ProcessBatch(items []Item) error {\n for i, item := range items {\n if err := process(item); err != nil {\n return fmt.Errorf(\"item %d: %w\", i, err)\n }\n }\n return nil\n}\n```\n\n### Recovery Workflow\n\nWhen you need old code back:\n1. `git log --oneline -20` - find the commit\n2. `git show \u003ccommit>:path/to/file` - view the old version\n3. `git checkout \u003ccommit> -- path/to/file` - restore if needed\n\n### When NOT to Apply\n\n- Active debugging session (delete before committing)\n- Code review showing before/after for context (use diff view instead)\n- Documentation explicitly showing what NOT to do\n\n### Benefits\n\n- Files are 10-30% shorter without commented code blocks\n- Clear intent: every line of code has a purpose\n- No confusion about what's active vs inactive\n- git blame shows actual history, not comment archaeology\n- Encourages proper use of version control\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3796,"content_sha256":"665b2668f05ce8ee77e9cdc9f57199c9e04349c18a0b9e0347e3f736edfe7481"},{"filename":"references/dead-keep-why-comments.md","content":"---\ntitle: Keep Comments That Explain Why, Not What\nimpact: MEDIUM\nimpactDescription: Why-comments preserve context, preventing 80% of \"cleanup\" bugs where devs break intentional behavior\ntags: dead, comments, documentation, context, intent\n---\n\n## Keep Comments That Explain Why, Not What\n\nCode shows what happens; only comments can explain why. Keep comments that capture business decisions, workarounds, non-obvious constraints, and historical context. These comments prevent future developers from \"fixing\" intentional behavior or repeating mistakes that led to the current implementation.\n\n**Incorrect (removing valuable context):**\n\n```typescript\n// Before removing comments:\nfunction processPayment(amount: number): boolean {\n // Visa requires amounts in cents, not dollars\n const centAmount = Math.round(amount * 100);\n\n // Retry limit set by PCI compliance audit (see JIRA-4521)\n const maxRetries = 3;\n\n // Must sleep 100ms between retries - payment gateway rate limits\n // Discovered during Black Friday 2023 outage\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n\n// After overzealous cleanup - WRONG:\nfunction processPayment(amount: number): boolean {\n const centAmount = Math.round(amount * 100);\n const maxRetries = 3;\n\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n// Future dev removes sleep(100) as \"unnecessary\" -> outage\n// Future dev changes maxRetries to 10 -> compliance violation\n```\n\n**Correct (preserve why comments):**\n\n```typescript\nfunction processPayment(amount: number): boolean {\n // Visa requires amounts in cents, not dollars\n const centAmount = Math.round(amount * 100);\n\n // Retry limit set by PCI compliance audit (JIRA-4521)\n const maxRetries = 3;\n\n // 100ms delay required by payment gateway rate limits (Black Friday 2023 postmortem)\n for (let i = 0; i \u003c maxRetries; i++) {\n if (gateway.charge(centAmount)) return true;\n sleep(100);\n }\n return false;\n}\n```\n\n**Comments worth keeping:**\n\n```python\n# Business rule: orders over $10k require manual approval (legal requirement)\nif order.total > 10000:\n order.status = \"pending_review\"\n\n# HACK: Safari doesn't support this API before v15, polyfill only for Safari\n# Remove after dropping Safari 14 support (EOL March 2024)\nif is_safari and version \u003c 15:\n load_polyfill()\n\n# WARNING: DO NOT change sort order - downstream systems depend on this\n# exact ordering for invoice reconciliation (see incident #892)\ntransactions.sort(key=lambda t: (t.date, t.id))\n\n# Performance: using raw SQL because ORM generates N+1 queries here\n# Benchmarked: 50ms vs 2.3s for 1000 records\ncursor.execute(RAW_QUERY, params)\n\n# Counterintuitive: we check for empty BEFORE validation because\n# empty arrays are valid (user clearing their cart) but the validator\n# rejects them. Business confirmed this behavior in Q3 product review.\nif not items:\n return Success(empty_cart)\n```\n\n**Comments to remove vs keep:**\n\n```javascript\n// REMOVE: States the obvious\nconst isActive = user.status === 'active'; // Check if user is active\n\n// KEEP: Explains non-obvious business rule\nconst isActive = user.status === 'active'; // \"suspended\" users can still view but not purchase\n\n// REMOVE: Describes the code\nfor (const item of items) { // Loop through items\n process(item);\n}\n\n// KEEP: Explains why this approach was chosen\nfor (const item of items) { // forEach breaks on async - must use for...of\n await process(item);\n}\n\n// REMOVE: Documents obvious type\nlet count: number = 0; // Number to track count\n\n// KEEP: Documents why type is unusual\nlet count: number = 0; // Must be number (not bigint) for legacy API compatibility\n```\n\n### Categories of Why Comments Worth Keeping\n\n1. **Business rules**: Legal, compliance, contractual requirements\n2. **Workarounds**: Browser bugs, library quirks, API limitations\n3. **Performance**: Why a non-obvious approach was faster\n4. **Historical**: Incidents, postmortems, decisions that led here\n5. **Warnings**: Things that look wrong but are intentional\n\n### Benefits\n\n- Preserves institutional knowledge\n- Prevents regression of intentional behavior\n- Reduces \"why is this here?\" Slack messages\n- Makes code archaeology faster during incidents\n- Protects against well-meaning \"cleanup\" that breaks things\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4405,"content_sha256":"79037caa28ee4269597932c109a52edb4105ed0c0477c491fb725c4f4ce6350f"},{"filename":"references/dead-remove-obvious-comments.md","content":"---\ntitle: Remove Comments That State the Obvious\nimpact: MEDIUM\nimpactDescription: Removing redundant comments cuts 30-50% of comment lines without information loss, and prevents comment drift that misleads 1 in 5 readers\ntags: dead, comments, redundancy, self-documenting\n---\n\n## Remove Comments That State the Obvious\n\nComments that repeat what the code says add noise without value. They double the reading burden and inevitably drift out of sync with the code they describe. Well-named variables and functions are self-documenting; comments should add context the code cannot express.\n\n**Incorrect (comments repeat the code):**\n\n```typescript\n// Import React\nimport React from 'react';\n\n// User interface\ninterface User {\n id: string; // The user's ID\n name: string; // The user's name\n email: string; // The user's email\n age: number; // The user's age\n}\n\n// Function to get user by ID\nfunction getUserById(id: string): User | null {\n // Find the user in the array\n const user = users.find(u => u.id === id);\n\n // If user is not found, return null\n if (!user) {\n return null;\n }\n\n // Return the user\n return user;\n}\n\n// Increment counter\ncounter++;\n\n// Set loading to true\nsetLoading(true);\n\n// Loop through items\nfor (const item of items) {\n // Process the item\n processItem(item);\n}\n```\n\n**Correct (self-documenting code, no redundant comments):**\n\n```typescript\nimport React from 'react';\n\ninterface User {\n id: string;\n name: string;\n email: string;\n age: number;\n}\n\nfunction getUserById(id: string): User | null {\n return users.find(u => u.id === id) ?? null;\n}\n\ncounter++;\nsetLoading(true);\n\nfor (const item of items) {\n processItem(item);\n}\n```\n\n**Incorrect (comments describe obvious logic):**\n\n```python\ndef calculate_total(items):\n # Initialize total to zero\n total = 0\n\n # Loop through each item\n for item in items:\n # Add the item price to total\n total += item.price\n\n # If item has discount, subtract it\n if item.discount:\n total -= item.discount\n\n # Return the total\n return total\n```\n\n**Correct (code speaks for itself):**\n\n```python\ndef calculate_total(items):\n total = 0\n for item in items:\n total += item.price\n if item.discount:\n total -= item.discount\n return total\n```\n\n**Incorrect (trivial getter/setter comments):**\n\n```java\npublic class Product {\n private String name;\n private double price;\n\n /**\n * Gets the name.\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * Sets the name.\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Gets the price.\n * @return the price\n */\n public double getPrice() {\n return price;\n }\n}\n```\n\n**Correct (skip trivial documentation):**\n\n```java\npublic class Product {\n private String name;\n private double price;\n\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n public double getPrice() { return price; }\n}\n```\n\n### What Makes a Comment Obvious?\n\n- Restates the identifier name: `// the user's name` for `userName`\n- Describes the language construct: `// loop through items` for a for loop\n- Explains standard operations: `// return the result`\n- Documents trivial getters/setters with no logic\n\n### When NOT to Apply\n\n- Regex patterns that need explanation\n- Complex algorithms that benefit from step descriptions\n- Non-obvious hardcoded numbers or business rules\n- Workarounds for known bugs or platform quirks\n- Public API documentation (JSDoc, docstrings)\n\n### Benefits\n\n- 30-50% fewer comment lines without information loss\n- Comments that remain are actually valuable\n- Reduces maintenance burden of keeping comments in sync\n- Forces better naming instead of relying on comments\n- Faster code scanning without visual noise\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3952,"content_sha256":"4e415b8e2bd0be04075317dd4672d4866a5b165f17c32ec73b37993f6639b8ec"},{"filename":"references/dead-remove-todo-fixme.md","content":"---\ntitle: Remove Stale TODO/FIXME Comments\nimpact: MEDIUM\nimpactDescription: Codebases average 200-500 stale TODOs; removing them reduces noise by 80% and makes urgent FIXMEs 3-5x more visible\ntags: dead, comments, todo, fixme, issues, tracking\n---\n\n## Remove Stale TODO/FIXME Comments\n\nTODO and FIXME comments are promises that rarely get kept. They accumulate over months and years until codebases have hundreds of stale reminders that everyone ignores. Either convert TODOs to tracked issues with owners and deadlines, or delete them. If something matters, it belongs in your issue tracker.\n\n**Incorrect (accumulated stale TODOs):**\n\n```typescript\nexport class UserService {\n // TODO: add caching\n // FIXME: this is slow\n // TODO: refactor this whole class (2019-03-15)\n // HACK: temporary fix for login bug\n // XXX: revisit this later\n\n async getUser(id: string): Promise\u003cUser> {\n // TODO: handle the case where user doesn't exist\n // FIXME: should validate id format\n const user = await this.db.query(`SELECT * FROM users WHERE id = ?`, [id]);\n\n // TODO: add proper error handling\n // TODO: log this somewhere\n // NOTE: Bob said to fix this - not sure what he meant\n return user;\n }\n\n // TODO(john): finish implementing this\n // TODO: write tests\n async updateUser(id: string, data: Partial\u003cUser>): Promise\u003cvoid> {\n // FIXME: SQL injection vulnerability!!!\n await this.db.query(`UPDATE users SET ${data} WHERE id = ${id}`);\n }\n}\n```\n\n**Correct (clean code, issues in tracker):**\n\n```typescript\nexport class UserService {\n async getUser(id: string): Promise\u003cUser | null> {\n const user = await this.db.query(`SELECT * FROM users WHERE id = ?`, [id]);\n return user ?? null;\n }\n\n async updateUser(id: string, data: Partial\u003cUser>): Promise\u003cvoid> {\n // Security: parameterized query prevents SQL injection\n const setClauses = Object.keys(data).map(k => `${k} = ?`).join(', ');\n await this.db.query(\n `UPDATE users SET ${setClauses} WHERE id = ?`,\n [...Object.values(data), id]\n );\n }\n}\n\n// Issue tracker entries created:\n// - PROJ-1234: Add Redis caching layer to UserService\n// - PROJ-1235: Add input validation for user ID format\n// - PROJ-1236: Implement proper error handling in data layer\n```\n\n**Incorrect (TODOs with no actionable path):**\n\n```python\n# TODO: make this better\ndef process_data(data):\n # FIXME: ugly code\n result = []\n for item in data:\n # TODO: optimize this\n if item.value > 0:\n result.append(item)\n # TODO: think about edge cases\n return result\n\n# TODO: might need to change this someday\nMAX_RETRIES = 3\n\n# FIXME: ???\ndef mystery_function():\n pass\n```\n\n**Correct (either fix it or delete the noise):**\n\n```python\ndef process_data(data):\n return [item for item in data if item.value > 0]\n\nMAX_RETRIES = 3\n\ndef mystery_function():\n pass # Intentionally empty - interface placeholder for plugins\n```\n\n**When a TODO is acceptable (temporarily):**\n\n```javascript\n// Acceptable: Specific, dated, with ticket reference\n// TODO(2024-Q1): Remove after migrating to v2 API (JIRA-5678)\nconst legacyAdapter = createLegacyAdapter();\n\n// Acceptable: Blocking issue documented\n// FIXME: Blocked on upstream PR#123 - using workaround until merged\nconst result = workaroundFunction();\n\n// Acceptable: Part of active PR/branch\n// TODO: Add error handling - will address in next commit\n```\n\n### TODO Triage Process\n\nWhen you find a TODO, decide:\n1. **Fix it now** - If it takes \u003c 5 minutes, just do it\n2. **Create issue** - If it's real work, track it properly\n3. **Delete it** - If it's vague, stale, or no longer relevant\n\n### Signs a TODO is Stale\n\n- Date older than 6 months\n- Author no longer on team\n- References completed work or old versions\n- Vague (\"make better\", \"fix this\", \"???\")\n- No one knows why it's there\n\n### Benefits\n\n- Issue tracker becomes single source of truth\n- TODO count stays near zero (easy to spot new ones)\n- Urgent FIXMEs don't get lost in noise\n- Code review can focus on real issues\n- New developers don't inherit archaeological debt\n\n### References\n\n- Most IDEs can extract TODOs to tasks: \"TODO to Issue\" extensions\n- CI tools can fail builds on TODO count thresholds\n- `grep -r \"TODO\\|FIXME\" --include=\"*.ts\" | wc -l` for auditing\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4293,"content_sha256":"df17442d626f543ffc6777ffd374e084bd89c87ec49e971342ecb540868bc1b2"},{"filename":"references/dead-remove-unused.md","content":"---\ntitle: Delete Unused Code Artifacts\nimpact: MEDIUM\nimpactDescription: Removing unused code reduces file size by 20-40% in cluttered files and eliminates false dependency signals that add 5-10 minutes per refactoring session\ntags: dead, unused, variables, functions, imports, parameters\n---\n\n## Delete Unused Code Artifacts\n\nUnused variables, functions, imports, and parameters are noise that obscures the real logic. They force readers to track dead references, bloat bundle sizes, and create phantom dependencies that complicate refactoring. Modern tooling catches unused code - delete it immediately rather than leaving it \"just in case.\"\n\n**Incorrect (unused artifacts throughout):**\n\n```typescript\nimport { useState, useEffect, useCallback, useMemo } from 'react';\nimport { formatDate, parseDate, isValidDate } from './dateUtils';\nimport { API_URL, MAX_RETRIES, TIMEOUT } from './constants';\n\ninterface UserListProps {\n users: User[];\n onSelect: (user: User) => void;\n showAvatar: boolean; // Never used in component\n maxItems: number; // Never used in component\n}\n\nexport function UserList({ users, onSelect, showAvatar, maxItems }: UserListProps) {\n const [selectedId, setSelectedId] = useState\u003cstring | null>(null);\n const [isLoading, setIsLoading] = useState(false); // Never used\n const [error, setError] = useState\u003cError | null>(null); // Never used\n\n const sortedUsers = useMemo(() => users, [users]); // Memo does nothing\n\n const handleClick = useCallback((user: User) => {\n setSelectedId(user.id);\n onSelect(user);\n }, [onSelect]);\n\n const unusedHelper = (data: unknown) => { // Never called\n return formatDate(data as Date);\n };\n\n return (\n \u003cul>\n {sortedUsers.map(user => (\n \u003cli key={user.id} onClick={() => handleClick(user)}>\n {user.name}\n \u003c/li>\n ))}\n \u003c/ul>\n );\n}\n```\n\n**Correct (only what's needed):**\n\n```typescript\nimport { useState, useCallback } from 'react';\n\ninterface UserListProps {\n users: User[];\n onSelect: (user: User) => void;\n}\n\nexport function UserList({ users, onSelect }: UserListProps) {\n const [selectedId, setSelectedId] = useState\u003cstring | null>(null);\n\n const handleClick = useCallback((user: User) => {\n setSelectedId(user.id);\n onSelect(user);\n }, [onSelect]);\n\n return (\n \u003cul>\n {users.map(user => (\n \u003cli key={user.id} onClick={() => handleClick(user)}>\n {user.name}\n \u003c/li>\n ))}\n \u003c/ul>\n );\n}\n```\n\n**Incorrect (unused function parameters):**\n\n```python\ndef calculate_discount(price, quantity, customer_type, region, currency, promo_code):\n \"\"\"Only price and quantity are actually used.\"\"\"\n return price * quantity * 0.9\n\ndef process_order(order, config, logger, metrics, cache):\n \"\"\"Only order is used.\"\"\"\n return order.total\n```\n\n**Correct (remove unused parameters or mark intentionally ignored):**\n\n```python\ndef calculate_discount(price, quantity):\n return price * quantity * 0.9\n\ndef process_order(order, _config, _logger, _metrics, _cache):\n \"\"\"Underscore prefix signals intentionally unused (interface compliance).\"\"\"\n return order.total\n```\n\n### When NOT to Apply\n\n- Interface compliance requires the parameter signature (use underscore prefix)\n- Public API where removal would be a breaking change\n- Parameters used only in debug/logging modes\n- Imports used only in type annotations (may appear unused to some tools)\n\n### Benefits\n\n- 20-40% reduction in lines of code in cluttered files\n- Faster code comprehension for new developers\n- Smaller bundle sizes (tree-shaking works better)\n- Clearer dependency graphs for refactoring tools\n- Eliminates false positives in static analysis\n\n### References\n\n- ESLint: no-unused-vars, no-unused-imports\n- TypeScript: noUnusedLocals, noUnusedParameters\n- Python: F401 (unused import), F841 (unused variable)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3846,"content_sha256":"3ca3f26c2a0516709988896e590f1251020fda2b201d347ac63d9db8ef4ee4b7"},{"filename":"references/dup-avoid-over-abstraction.md","content":"---\ntitle: Prefer Duplication Over Premature Abstraction\nimpact: MEDIUM\nimpactDescription: Wrong abstractions cost 3-10x more to fix than duplicated code, and force unrelated code to change together\ntags: dup, abstraction, coupling, maintainability\n---\n\n## Prefer Duplication Over Premature Abstraction\n\nThree similar lines of code are often better than a premature abstraction. The wrong abstraction creates coupling between unrelated concepts, making future changes ripple across the codebase. Duplication is cheap to fix later when you understand the true pattern; bad abstractions are expensive to unwind because other code depends on them.\n\n**Incorrect (premature abstraction couples unrelated concepts):**\n\n```typescript\n// \"Both format currency, let's make it generic!\"\nfunction formatValue(value: number, type: 'price' | 'salary' | 'discount'): string {\n const symbol = type === 'discount' ? '-

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

: '

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

;\n const decimals = type === 'salary' ? 0 : 2;\n const prefix = type === 'price' ? '' : ' ';\n\n return `${prefix}${symbol}${value.toFixed(decimals)}`;\n}\n\n// Now price formatting changes require checking salary and discount logic\n// And discount needs a negative sign but price doesn't\n// The abstraction becomes a mess of special cases\n```\n\n**Correct (explicit duplication until patterns emerge):**\n\n```typescript\nfunction formatPrice(cents: number): string {\n return `${(cents / 100).toFixed(2)}`;\n}\n\nfunction formatSalary(annual: number): string {\n return `${annual.toLocaleString()}`;\n}\n\nfunction formatDiscount(cents: number): string {\n return `-${(cents / 100).toFixed(2)}`;\n}\n\n// Each can evolve independently\n// formatPrice might add currency symbols later\n// formatSalary might add \"per year\" suffix\n// formatDiscount might show percentage instead\n```\n\n**Incorrect (abstraction forces unrelated code to change together):**\n\n```python\nclass EntityProcessor:\n \"\"\"Processes users, orders, and products - they're all 'entities'!\"\"\"\n\n def process(self, entity, entity_type):\n if entity_type == 'user':\n self._validate_user(entity)\n self._save_user(entity)\n elif entity_type == 'order':\n self._validate_order(entity)\n self._calculate_totals(entity)\n self._save_order(entity)\n elif entity_type == 'product':\n self._validate_product(entity)\n self._update_inventory(entity)\n self._save_product(entity)\n\n# Adding a new entity type or changing one affects this god class\n# User processing doesn't need inventory; order doesn't need user validation\n```\n\n**Correct (separate concerns, accept some duplication):**\n\n```python\nclass UserService:\n def create_user(self, data):\n self._validate(data)\n return self.repository.save(data)\n\nclass OrderService:\n def create_order(self, data):\n self._validate(data)\n self._calculate_totals(data)\n return self.repository.save(data)\n\nclass ProductService:\n def create_product(self, data):\n self._validate(data)\n self._update_inventory(data)\n return self.repository.save(data)\n\n# Yes, each has _validate and save - that's okay\n# They can diverge without affecting each other\n```\n\n**Incorrect (abstracting over superficial similarity):**\n\n```go\n// \"Both take a slice and return one element!\"\nfunc getOne[T any](items []T, selector func([]T) T) T {\n return selector(items)\n}\n\n// Callers become puzzling\nfirst := getOne(users, func(u []User) User { return u[0] })\nlast := getOne(orders, func(o []Order) Order { return o[len(o)-1] })\nrandom := getOne(products, func(p []Product) Product {\n return p[rand.Intn(len(p))]\n})\n```\n\n**Correct (just write the simple code):**\n\n```go\nfirst := users[0]\nlast := orders[len(orders)-1]\nrandom := products[rand.Intn(len(products))]\n\n// Obvious, no abstraction needed\n```\n\n**Incorrect (DRY violation fear leads to tight coupling):**\n\n```javascript\n// Shared validation \"to avoid duplication\"\nconst sharedValidation = {\n validateEmail: (email) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email),\n validatePhone: (phone) => /^\\d{10}$/.test(phone),\n};\n\n// Now used by User, Contact, Company, Lead...\n// Phone validation needs to change for international numbers\n// But only for Company and Lead, not User\n// The \"shared\" code becomes a liability\n```\n\n**Correct (duplicate until requirements clarify):**\n\n```javascript\n// User module\nfunction validateUserPhone(phone) {\n return /^\\d{10}$/.test(phone); // US only for users\n}\n\n// Company module\nfunction validateCompanyPhone(phone) {\n return /^\\+?[\\d\\s-]{10,}$/.test(phone); // International for business\n}\n\n// When you KNOW they should be the same, then extract\n```\n\n### The Sandi Metz Rule\n\n\"Duplication is far cheaper than the wrong abstraction.\" If you're unsure whether code should be shared:\n\n1. Duplicate it\n2. Wait for the third occurrence\n3. Look for the true underlying pattern\n4. Then extract with confidence\n\n### When Abstraction IS Appropriate\n\n- Business rule that must be consistent (tax calculation, authentication)\n- Algorithm that is complex and needs isolated testing\n- Pattern that has appeared 3+ times with identical structure\n- Domain concept with a clear name in the ubiquitous language\n\n### Benefits\n\n- Code changes are localized to one area\n- New requirements don't break unrelated features\n- Easier to understand - each module is self-contained\n- Refactoring is straightforward when patterns emerge\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5433,"content_sha256":"fec1b3424813f7dc29ac6d21ebaf4eab85cd474e9338d18c75353137f42914f9"},{"filename":"references/dup-data-driven.md","content":"---\ntitle: Use Data-Driven Patterns Over Repetitive Conditionals\nimpact: MEDIUM\nimpactDescription: Data-driven approaches reduce conditional branches by 60-80% and make adding new cases a one-line change instead of copy-paste\ntags: dup, data-driven, conditionals, maps, configuration\n---\n\n## Use Data-Driven Patterns Over Repetitive Conditionals\n\nWhen you have repetitive if/else or switch statements that map inputs to outputs, replace them with data structures like maps, lookup tables, or configuration objects. Data-driven code is easier to extend (add a line, not a branch), easier to test (validate the data structure), and less prone to copy-paste errors.\n\n**Incorrect (repetitive conditionals):**\n\n```typescript\nfunction getStatusColor(status: string): string {\n if (status === 'pending') {\n return '#FFA500';\n } else if (status === 'approved') {\n return '#00FF00';\n } else if (status === 'rejected') {\n return '#FF0000';\n } else if (status === 'cancelled') {\n return '#808080';\n } else if (status === 'processing') {\n return '#0000FF';\n } else if (status === 'completed') {\n return '#00AA00';\n } else {\n return '#000000';\n }\n}\n// Adding a new status = new branch + risk of typo\n```\n\n**Correct (data-driven lookup):**\n\n```typescript\nconst STATUS_COLORS: Record\u003cstring, string> = {\n pending: '#FFA500',\n approved: '#00FF00',\n rejected: '#FF0000',\n cancelled: '#808080',\n processing: '#0000FF',\n completed: '#00AA00',\n};\n\nfunction getStatusColor(status: string): string {\n return STATUS_COLORS[status] ?? '#000000';\n}\n// Adding a new status = one line in the map\n```\n\n**Incorrect (switch statement for validation rules):**\n\n```python\ndef validate_field(field_type, value):\n if field_type == 'email':\n if not re.match(r'^[\\w.-]+@[\\w.-]+\\.\\w+

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, value):\n return 'Invalid email format'\n elif field_type == 'phone':\n if not re.match(r'^\\d{10}

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, value):\n return 'Phone must be 10 digits'\n elif field_type == 'zip':\n if not re.match(r'^\\d{5}(-\\d{4})?

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, value):\n return 'Invalid ZIP code'\n elif field_type == 'ssn':\n if not re.match(r'^\\d{3}-\\d{2}-\\d{4}

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, value):\n return 'Invalid SSN format'\n # ... 20 more field types\n return None\n```\n\n**Correct (configuration-driven validation):**\n\n```python\nFIELD_VALIDATORS = {\n 'email': (r'^[\\w.-]+@[\\w.-]+\\.\\w+

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, 'Invalid email format'),\n 'phone': (r'^\\d{10}

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, 'Phone must be 10 digits'),\n 'zip': (r'^\\d{5}(-\\d{4})?

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, 'Invalid ZIP code'),\n 'ssn': (r'^\\d{3}-\\d{2}-\\d{4}

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…

, 'Invalid SSN format'),\n}\n\ndef validate_field(field_type: str, value: str) -> str | None:\n if field_type not in FIELD_VALIDATORS:\n return None\n\n pattern, error_message = FIELD_VALIDATORS[field_type]\n if not re.match(pattern, value):\n return error_message\n return None\n# New field type = one line in FIELD_VALIDATORS\n```\n\n**Incorrect (factory with repetitive instantiation):**\n\n```go\nfunc CreateHandler(handlerType string) Handler {\n switch handlerType {\n case \"json\":\n return &JSONHandler{\n ContentType: \"application/json\",\n Encoder: json.Marshal,\n }\n case \"xml\":\n return &XMLHandler{\n ContentType: \"application/xml\",\n Encoder: xml.Marshal,\n }\n case \"yaml\":\n return &YAMLHandler{\n ContentType: \"application/yaml\",\n Encoder: yaml.Marshal,\n }\n // ... more handlers\n }\n return nil\n}\n```\n\n**Correct (registry pattern):**\n\n```go\ntype HandlerConfig struct {\n ContentType string\n Encoder func(any) ([]byte, error)\n}\n\nvar handlerRegistry = map[string]HandlerConfig{\n \"json\": {\"application/json\", json.Marshal},\n \"xml\": {\"application/xml\", xml.Marshal},\n \"yaml\": {\"application/yaml\", yaml.Marshal},\n}\n\nfunc CreateHandler(handlerType string) Handler {\n config, ok := handlerRegistry[handlerType]\n if !ok {\n return nil\n }\n return NewHandler(config)\n}\n// Adding a handler = one line in registry\n```\n\n**Incorrect (under-abstraction - missing data-driven opportunity):**\n\n```javascript\nfunction calculateShipping(country) {\n if (country === 'US') return 5.99;\n if (country === 'CA') return 9.99;\n if (country === 'MX') return 12.99;\n if (country === 'UK') return 15.99;\n if (country === 'DE') return 15.99;\n if (country === 'FR') return 15.99;\n if (country === 'JP') return 25.99;\n if (country === 'AU') return 29.99;\n return 35.99; // International\n}\n// Europe has same price but requires 3 lines\n```\n\n**Correct (data structure reveals patterns):**\n\n```javascript\nconst SHIPPING_RATES = {\n domestic: { US: 5.99 },\n northAmerica: { CA: 9.99, MX: 12.99 },\n europe: { UK: 15.99, DE: 15.99, FR: 15.99, ES: 15.99, IT: 15.99 },\n pacific: { JP: 25.99, AU: 29.99, NZ: 29.99 },\n default: 35.99,\n};\n\nfunction calculateShipping(country) {\n for (const region of Object.values(SHIPPING_RATES)) {\n if (typeof region === 'object' && country in region) {\n return region[country];\n }\n }\n return SHIPPING_RATES.default;\n}\n// Structure reveals business logic: regions have shared pricing\n```\n\n### When NOT to Use Data-Driven\n\n- When branches have complex logic, not just value mapping\n- When there are only 2-3 cases and they're unlikely to grow\n- When the \"data\" would be as complex as the code it replaces\n\n### Benefits\n\n- Adding new cases is a configuration change, not code change\n- Data can be loaded from external sources (database, config files)\n- Easier to test - validate the data structure separately\n- Business rules are visible at a glance in the data structure\n- Reduces cyclomatic complexity significantly\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5677,"content_sha256":"ef0a708d76846c75cb2a8a4df61cf553c02256db3846c1c6785a10b5d862212f"},{"filename":"references/dup-extract-for-clarity.md","content":"---\ntitle: Extract Only When It Improves Clarity\nimpact: MEDIUM\nimpactDescription: Poor extractions increase code navigation time by 40-60% and obscure business logic behind generic names\ntags: dup, clarity, readability, naming, abstraction\n---\n\n## Extract Only When It Improves Clarity\n\nExtraction should make code easier to understand, not just shorter. If the extracted function name doesn't communicate intent better than the original code, keep the code inline. A helper called `processData()` or `handleStuff()` forces readers to look inside anyway. The goal is comprehension, not line count reduction.\n\n**Incorrect (extraction hides intent behind vague name):**\n\n```typescript\nasync function checkout(cart: Cart): Promise\u003cOrder> {\n const order = await processCartData(cart);\n await finalizeOrder(order);\n return order;\n}\n\n// What does this do? Must read implementation\nasync function processCartData(cart: Cart): Promise\u003cOrder> {\n const items = cart.items.filter(item => item.quantity > 0);\n const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n const tax = subtotal * 0.08;\n return { items, subtotal, tax, total: subtotal + tax };\n}\n```\n\n**Correct (inline code that speaks for itself):**\n\n```typescript\nasync function checkout(cart: Cart): Promise\u003cOrder> {\n const items = cart.items.filter(item => item.quantity > 0);\n const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n const tax = subtotal * 0.08;\n\n const order: Order = { items, subtotal, tax, total: subtotal + tax };\n await this.orderRepository.save(order);\n await this.emailService.sendConfirmation(order);\n\n return order;\n}\n// Business logic is immediately visible\n```\n\n**Incorrect (extracting trivial operations):**\n\n```python\ndef create_report(data):\n filtered = filter_empty_records(data)\n sorted_data = sort_by_date(filtered)\n return format_as_table(sorted_data)\n\ndef filter_empty_records(data):\n return [r for r in data if r] # One-liner hidden behind function\n\ndef sort_by_date(data):\n return sorted(data, key=lambda x: x['date']) # One-liner hidden\n\ndef format_as_table(data):\n # Actually complex - this extraction is justified\n ...\n```\n\n**Correct (extract complex, inline simple):**\n\n```python\ndef create_report(data):\n records = [r for r in data if r] # Filter empty - obvious\n records.sort(key=lambda x: x['date']) # Sort by date - obvious\n\n return format_as_table(records) # Complex formatting - good extraction\n\ndef format_as_table(records):\n \"\"\"Convert records to ASCII table with headers and alignment.\"\"\"\n # 30 lines of table formatting logic\n ...\n```\n\n**Incorrect (generic names that require reading implementation):**\n\n```go\nfunc HandleRequest(r *Request) (*Response, error) {\n if err := doValidation(r); err != nil {\n return nil, err\n }\n result := doProcessing(r)\n return doFormatting(result), nil\n}\n\nfunc doValidation(r *Request) error { ... }\nfunc doProcessing(r *Request) *Result { ... }\nfunc doFormatting(r *Result) *Response { ... }\n// \"do\" prefix is a code smell - names don't describe behavior\n```\n\n**Correct (names that describe actual behavior):**\n\n```go\nfunc HandleRequest(r *Request) (*Response, error) {\n if err := validateRequestSchema(r); err != nil {\n return nil, err\n }\n inventory := checkInventoryLevels(r.Items)\n return formatInventoryResponse(inventory), nil\n}\n\nfunc validateRequestSchema(r *Request) error { ... }\nfunc checkInventoryLevels(items []Item) *InventoryStatus { ... }\nfunc formatInventoryResponse(status *InventoryStatus) *Response { ... }\n// Each name tells you what the function does without reading it\n```\n\n**Incorrect (DRY obsession - extracting unrelated similar code):**\n\n```javascript\n// \"These both iterate arrays, let's extract!\"\nfunction processItems(items, processor) {\n const results = [];\n for (const item of items) {\n results.push(processor(item));\n }\n return results;\n}\n\n// Callers now obscure their intent\nconst prices = processItems(products, p => p.price);\nconst names = processItems(users, u => u.name);\n```\n\n**Correct (use language features, keep intent clear):**\n\n```javascript\nconst prices = products.map(p => p.price);\nconst names = users.map(u => u.name);\n// Array.map is universally understood - no custom abstraction needed\n```\n\n### Signs That Extraction Improves Clarity\n\n- The function name explains a \"why\" that code alone doesn't convey\n- The function encapsulates a business rule that has a domain name\n- Readers can understand the calling code without reading the helper\n- The extracted logic is cohesive and represents one concept\n\n### Signs That Extraction Hurts Clarity\n\n- You struggle to name the function (vague names like `process`, `handle`, `do`)\n- The function name is longer than the code it contains\n- Readers still need to check the implementation to understand the caller\n- The extraction groups unrelated operations\n\n### Benefits\n\n- Code reads like documentation of business logic\n- Reduced navigation between files and functions\n- Function names serve as accurate documentation\n- New team members understand code faster\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5146,"content_sha256":"a3d8ef58a545484db0ae939c20d5163908dafc2c74e1a0bed79c3181a6ad91ce"},{"filename":"references/dup-no-single-use-helpers.md","content":"---\ntitle: Avoid Single-Use Helper Functions\nimpact: MEDIUM\nimpactDescription: Each unnecessary helper adds 30-60 seconds of navigation time and fragments code comprehension across multiple locations\ntags: dup, helpers, abstraction, indirection\n---\n\n## Avoid Single-Use Helper Functions\n\nDo not extract code into a helper function if it will only be called from one place. Single-use helpers fragment logic across multiple locations, forcing readers to jump between files or scroll to understand what should be a single coherent operation. The cure is worse than the disease - you trade local complexity for distributed complexity.\n\n**Incorrect (single-use helper obscures logic):**\n\n```typescript\n// In userService.ts\nasync function createUser(data: UserInput): Promise\u003cUser> {\n const validated = await validateUserInput(data);\n const normalized = normalizeUserData(validated);\n const user = await saveUser(normalized);\n await sendWelcomeNotification(user);\n return user;\n}\n\n// In userHelpers.ts - only called once!\nfunction normalizeUserData(data: ValidatedUserInput): NormalizedUser {\n return {\n email: data.email.toLowerCase().trim(),\n name: data.name.trim(),\n createdAt: new Date(),\n };\n}\n// Reader must now open another file to understand createUser\n```\n\n**Correct (inline single-use logic):**\n\n```typescript\nasync function createUser(data: UserInput): Promise\u003cUser> {\n const validated = await validateUserInput(data);\n\n const normalized: NormalizedUser = {\n email: validated.email.toLowerCase().trim(),\n name: validated.name.trim(),\n createdAt: new Date(),\n };\n\n const user = await saveUser(normalized);\n await sendWelcomeNotification(user);\n return user;\n}\n// All logic visible in one place\n```\n\n**Incorrect (over-extraction for \"cleanliness\"):**\n\n```python\nclass OrderProcessor:\n def process_order(self, order):\n self._validate_inventory(order)\n self._calculate_totals(order)\n self._apply_discounts(order)\n self._save_order(order)\n\n def _validate_inventory(self, order):\n # 3 lines of code, called only here\n for item in order.items:\n if item.quantity > self.inventory[item.sku]:\n raise InsufficientInventoryError(item.sku)\n\n def _calculate_totals(self, order):\n # 2 lines of code, called only here\n order.subtotal = sum(item.price * item.quantity for item in order.items)\n order.total = order.subtotal + order.shipping\n\n # ... more single-use private methods\n# Class is now 150 lines but process_order reads like a mystery novel\n```\n\n**Correct (inline when logic is simple and single-use):**\n\n```python\nclass OrderProcessor:\n def process_order(self, order):\n # Validate inventory\n for item in order.items:\n if item.quantity > self.inventory[item.sku]:\n raise InsufficientInventoryError(item.sku)\n\n # Calculate totals\n order.subtotal = sum(item.price * item.quantity for item in order.items)\n order.total = order.subtotal + order.shipping\n\n # Apply discounts (this IS complex - worth extracting)\n self._apply_discount_rules(order)\n\n self.repository.save(order)\n# Comments provide structure; complex logic gets extracted\n```\n\n**Incorrect (extracting for testability when integration test suffices):**\n\n```go\nfunc ProcessPayment(order *Order) error {\n if err := validatePaymentDetails(order); err != nil {\n return err\n }\n return chargeCard(order)\n}\n\n// Extracted \"for testability\" but only called once\nfunc validatePaymentDetails(order *Order) error {\n if order.Amount \u003c= 0 {\n return errors.New(\"invalid amount\")\n }\n if order.CardToken == \"\" {\n return errors.New(\"missing card token\")\n }\n return nil\n}\n```\n\n**Correct (test through the public interface):**\n\n```go\nfunc ProcessPayment(order *Order) error {\n if order.Amount \u003c= 0 {\n return errors.New(\"invalid amount\")\n }\n if order.CardToken == \"\" {\n return errors.New(\"missing card token\")\n }\n return chargeCard(order)\n}\n// Test ProcessPayment with invalid inputs directly\n```\n\n### When Single-Use Helpers ARE Appropriate\n\n- Function exceeds 50 lines and has clear logical sections\n- Logic requires extensive comments that would benefit from a descriptive name\n- Testing the helper in isolation provides significant value\n- The helper encapsulates a complex algorithm that deserves its own tests\n\n### Benefits\n\n- Code flows linearly without jumping between locations\n- Reduces file count and cognitive load\n- Makes debugging easier - stack traces are shorter\n- Faster code review - reviewers see complete logic in context\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4668,"content_sha256":"62f084489d070524c7e21879034df35bf51e7ccc66701fc3e007fad830b82316"},{"filename":"references/dup-rule-of-three.md","content":"---\ntitle: Apply the Rule of Three\nimpact: MEDIUM\nimpactDescription: Premature extraction adds 2-5 minutes of navigation overhead per reader; waiting for 3 occurrences reduces wrong abstractions by 60-80%\ntags: dup, abstraction, dry, timing\n---\n\n## Apply the Rule of Three\n\nWait until code appears three times before extracting a helper. The first duplication might be coincidental. The second confirms a pattern exists. The third proves extraction is worthwhile. Extracting too early creates abstractions for patterns that never materialize, adding cognitive overhead without reducing maintenance burden.\n\n**Incorrect (extracting after first duplication):**\n\n```typescript\n// Two similar validation calls - someone extracts immediately\nfunction validateUser(user: User) {\n if (!user.email.includes('@')) throw new Error('Invalid email');\n}\n\nfunction validateContact(contact: Contact) {\n if (!contact.email.includes('@')) throw new Error('Invalid email');\n}\n\n// Over-engineered \"solution\" after seeing just 2 occurrences\nfunction validateEmail(entity: { email: string }, entityName: string) {\n if (!entity.email.includes('@')) {\n throw new Error(`Invalid ${entityName} email`);\n }\n}\n// Now every caller needs to understand this abstraction\n// And if requirements diverge, the abstraction becomes awkward\n```\n\n**Correct (wait for the third occurrence):**\n\n```typescript\n// First occurrence\nfunction validateUser(user: User) {\n if (!user.email.includes('@')) throw new Error('Invalid email');\n}\n\n// Second occurrence - note it, don't extract yet\nfunction validateContact(contact: Contact) {\n if (!contact.email.includes('@')) throw new Error('Invalid email');\n}\n\n// Third occurrence - NOW extract with confidence\nfunction validateOrder(order: Order) {\n if (!order.customerEmail.includes('@')) throw new Error('Invalid email');\n}\n\n// After third occurrence, extract with full understanding of the pattern\nfunction isValidEmail(email: string): boolean {\n return email.includes('@');\n}\n```\n\n**Incorrect (under-extraction - ignoring obvious patterns):**\n\n```python\n# Same exact logic copy-pasted 5 times\ndef process_user_csv(filepath):\n with open(filepath, 'r') as f:\n reader = csv.DictReader(f)\n return [row for row in reader if row.get('active') == 'true']\n\ndef process_order_csv(filepath):\n with open(filepath, 'r') as f:\n reader = csv.DictReader(f)\n return [row for row in reader if row.get('active') == 'true']\n\ndef process_product_csv(filepath):\n with open(filepath, 'r') as f:\n reader = csv.DictReader(f)\n return [row for row in reader if row.get('active') == 'true']\n# Bug fix needed? Change it in 5 places\n```\n\n**Correct (extract after pattern is established):**\n\n```python\ndef load_active_records(filepath: str) -> list[dict]:\n \"\"\"Load records from CSV where active='true'.\"\"\"\n with open(filepath, 'r') as f:\n reader = csv.DictReader(f)\n return [row for row in reader if row.get('active') == 'true']\n\n# Clear, single source of truth\nusers = load_active_records('users.csv')\norders = load_active_records('orders.csv')\nproducts = load_active_records('products.csv')\n```\n\n### When NOT to Apply\n\n- Security-critical code (authentication, authorization) - extract immediately\n- Complex algorithms where bugs are likely - extract on second occurrence\n- When business logic dictates the pattern will recur (known requirements)\n\n### Benefits\n\n- Abstractions are based on real patterns, not speculation\n- Fewer premature abstractions that need refactoring later\n- Code readers encounter simpler, more concrete code\n- Easier to understand what each piece of code actually does\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3653,"content_sha256":"7f1433ce796e65296291fc23a74f90c7e19379ae646b3068ba1c3780cb11bae0"},{"filename":"references/flow-boolean-simplification.md","content":"---\ntitle: Simplify Boolean Expressions\nimpact: HIGH\nimpactDescription: Eliminates double negations and nested NOT operators that cause 2-3x longer comprehension time, reducing logical errors in conditions by 40-60%\ntags: flow, boolean, de-morgans, double-negation, conditions\n---\n\n## Simplify Boolean Expressions\n\nComplex boolean expressions with double negations, redundant comparisons, and tangled logic slow readers down and hide bugs. Apply De Morgan's laws, remove double negations, and compare directly to booleans to make conditions express their intent in the simplest possible form.\n\n**Incorrect (double negations and redundant comparisons):**\n\n```typescript\nfunction shouldShowBanner(user: User, settings: Settings): boolean {\n if (!(!user.isSubscribed)) {\n return false;\n }\n if (user.dismissed !== true && !settings.bannersDisabled) {\n return true;\n }\n return false;\n}\n\nfunction canAccess(role: string, isActive: boolean): boolean {\n if (!(role !== 'admin' && role !== 'moderator') === false) {\n return false;\n }\n return isActive !== false;\n}\n```\n\n**Correct (simplified booleans):**\n\n```typescript\nfunction shouldShowBanner(user: User, settings: Settings): boolean {\n if (user.isSubscribed) {\n return false;\n }\n return !user.dismissed && !settings.bannersDisabled;\n}\n\nfunction canAccess(role: string, isActive: boolean): boolean {\n if (role !== 'admin' && role !== 'moderator') {\n return false;\n }\n return isActive;\n}\n```\n\n**Incorrect (Python - verbose boolean logic):**\n\n```python\ndef is_valid_order(order):\n if not (order.total \u003c= 0) and not (len(order.items) == 0):\n if order.customer is not None and order.customer.verified == True:\n return True\n return False\n```\n\n**Correct (Python - direct boolean expressions):**\n\n```python\ndef is_valid_order(order):\n has_items = len(order.items) > 0\n has_positive_total = order.total > 0\n has_verified_customer = order.customer is not None and order.customer.verified\n\n return has_items and has_positive_total and has_verified_customer\n```\n\n**Incorrect (Go - nested negations in error checks):**\n\n```go\nfunc validateConfig(config *Config) error {\n if !(config.Host == \"\" || config.Port == 0) {\n if !(config.Timeout \u003c 0) {\n return nil\n }\n }\n return errors.New(\"invalid configuration\")\n}\n```\n\n**Correct (Go - positive conditions):**\n\n```go\nfunc validateConfig(config *Config) error {\n if config.Host == \"\" || config.Port == 0 {\n return errors.New(\"invalid configuration\")\n }\n if config.Timeout \u003c 0 {\n return errors.New(\"invalid configuration\")\n }\n return nil\n}\n```\n\n### Key Simplification Rules\n\n| Pattern | Simplifies To |\n|---------|---------------|\n| `!!x` | `x` |\n| `!(a && b)` | `!a \\|\\| !b` (De Morgan's) |\n| `!(a \\|\\| b)` | `!a && !b` (De Morgan's) |\n| `x === true` | `x` |\n| `x === false` | `!x` |\n| `x !== true` | `!x` |\n| `!(x !== y)` | `x === y` |\n\n### When NOT to Apply\n\n- When boolean variables are nullable (`x === true` explicitly excludes `null`/`undefined`)\n- When intermediate boolean names add meaningful domain context (extracting `isEligible` from a complex expression is good)\n- When the simplified form is actually harder to read than the expanded form\n\n### Benefits\n\n- Conditions express intent directly without mental inversion\n- Fewer logical operators means fewer places for bugs\n- Named intermediate booleans document the business logic\n- Code reviewers catch logical errors faster in simplified expressions\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3516,"content_sha256":"a445b9277c587a515fcc89132e15315f5b4f04ddfa0f264af6060ccb86f3d720"},{"filename":"references/flow-early-return.md","content":"---\ntitle: Use Early Returns to Reduce Nesting\nimpact: HIGH\nimpactDescription: Early returns reduce average nesting depth by 2-3 levels, cutting cognitive load by 40-60% per function\ntags: flow, nesting, readability, cognitive-load\n---\n\n## Use Early Returns to Reduce Nesting\n\nDeep nesting forces readers to mentally track multiple conditions simultaneously. Early returns eliminate wrapper conditions by handling edge cases immediately and exiting. This creates a linear reading flow where each line is at the same indentation level, dramatically improving comprehension.\n\n**Incorrect (deeply nested logic):**\n\n```typescript\nfunction processOrder(order: Order): Result {\n if (order) {\n if (order.items.length > 0) {\n if (order.customer) {\n if (order.customer.isActive) {\n if (order.paymentMethod) {\n const total = calculateTotal(order.items);\n if (total > 0) {\n const discount = getDiscount(order.customer);\n const finalTotal = total - discount;\n return chargeCustomer(order.customer, finalTotal);\n } else {\n return { error: 'Invalid total' };\n }\n } else {\n return { error: 'No payment method' };\n }\n } else {\n return { error: 'Customer inactive' };\n }\n } else {\n return { error: 'No customer' };\n }\n } else {\n return { error: 'No items' };\n }\n } else {\n return { error: 'No order' };\n }\n}\n```\n\n**Correct (early returns, flat structure):**\n\n```typescript\nfunction processOrder(order: Order): Result {\n if (!order) {\n return { error: 'No order' };\n }\n if (order.items.length === 0) {\n return { error: 'No items' };\n }\n if (!order.customer) {\n return { error: 'No customer' };\n }\n if (!order.customer.isActive) {\n return { error: 'Customer inactive' };\n }\n if (!order.paymentMethod) {\n return { error: 'No payment method' };\n }\n\n const total = calculateTotal(order.items);\n if (total \u003c= 0) {\n return { error: 'Invalid total' };\n }\n\n const discount = getDiscount(order.customer);\n const finalTotal = total - discount;\n return chargeCustomer(order.customer, finalTotal);\n}\n```\n\n### Benefits\n\n- Reading flow is top-to-bottom without mental stack\n- Error conditions are visually grouped at the top\n- Happy path is clearly visible at the bottom\n- Each condition can be understood in isolation\n- Easier to add new validations without restructuring\n\n### Related\n\n- See also [`flow-guard-clauses`](flow-guard-clauses.md) for validating preconditions at function entry\n\n### When NOT to Apply\n\n- When the nested structure represents meaningful domain hierarchy\n- In functional programming contexts where early return breaks composition\n- When using exhaustive pattern matching that requires all branches\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2833,"content_sha256":"6d8edaf84e6f985545c4f6d1e03121bd9ed4335e0af11f149ee41324fd64d545"},{"filename":"references/flow-explicit-over-dense.md","content":"---\ntitle: Prefer Explicit Control Flow Over Dense Expressions\nimpact: HIGH\nimpactDescription: Explicit code reduces debugging time by 50% and decreases bug introduction rate during modifications by 35%\ntags: flow, readability, explicit, dense-code, maintenance\n---\n\n## Prefer Explicit Control Flow Over Dense Expressions\n\nDense one-liners optimize for code golf, not comprehension. When multiple operations are chained or combined into a single expression, readers must mentally unpack each step. Explicit code may take more lines, but each line does one obvious thing. Future maintainers (including yourself) will thank you.\n\n**Incorrect (dense chained operations):**\n\n```typescript\nconst result = data.filter(x => x.active).map(x => x.value).reduce((a, b) => a + b, 0) / data.filter(x => x.active).length || 0;\n```\n\n**Correct (explicit steps with meaningful names):**\n\n```typescript\nconst activeItems = data.filter(item => item.active);\nconst values = activeItems.map(item => item.value);\nconst sum = values.reduce((total, value) => total + value, 0);\nconst average = activeItems.length > 0 ? sum / activeItems.length : 0;\n```\n\n**Incorrect (boolean logic golfing):**\n\n```typescript\nconst canProceed = !!(user && user.verified && (user.role === 'admin' || (user.role === 'member' && user.subscription?.active && new Date(user.subscription.expiresAt) > new Date())));\n```\n\n**Correct (readable boolean expression):**\n\n```typescript\nconst isVerifiedUser = user?.verified ?? false;\nconst isAdmin = user?.role === 'admin';\nconst hasActiveSubscription =\n user?.role === 'member' &&\n user?.subscription?.active &&\n new Date(user.subscription.expiresAt) > new Date();\n\nconst canProceed = isVerifiedUser && (isAdmin || hasActiveSubscription);\n```\n\n**Incorrect (clever short-circuit abuse):**\n\n```typescript\nfunction updateUser(id: string, data: Partial\u003cUser>) {\n const user = db.get(id) || (throwError('Not found'), null);\n data.email && validateEmail(data.email) || (throwError('Invalid email'), null);\n data.age && (data.age \u003c 0 || data.age > 150) && (throwError('Invalid age'), null);\n return db.update(id, { ...user, ...data, updatedAt: Date.now() });\n}\n```\n\n**Correct (explicit validation flow):**\n\n```typescript\nfunction updateUser(id: string, data: Partial\u003cUser>) {\n const user = db.get(id);\n if (!user) {\n throw new NotFoundError(`User ${id} not found`);\n }\n\n if (data.email !== undefined) {\n if (!validateEmail(data.email)) {\n throw new ValidationError('Invalid email format');\n }\n }\n\n if (data.age !== undefined) {\n if (data.age \u003c 0 || data.age > 150) {\n throw new ValidationError('Age must be between 0 and 150');\n }\n }\n\n return db.update(id, {\n ...user,\n ...data,\n updatedAt: Date.now(),\n });\n}\n```\n\n**Incorrect (compressed array building):**\n\n```typescript\nconst items = [...(showArchived ? archivedItems : []), ...activeItems.filter(i => !i.hidden), ...(includeDeleted && deletedItems || [])].sort((a, b) => a.date - b.date).slice(0, limit);\n```\n\n**Correct (step-by-step array construction):**\n\n```typescript\nconst items: Item[] = [];\n\nif (showArchived) {\n items.push(...archivedItems);\n}\n\nconst visibleActive = activeItems.filter(item => !item.hidden);\nitems.push(...visibleActive);\n\nif (includeDeleted && deletedItems) {\n items.push(...deletedItems);\n}\n\nitems.sort((a, b) => a.date - b.date);\nconst limitedItems = items.slice(0, limit);\n```\n\n### Benefits\n\n- Each line can be understood independently\n- Intermediate values can be logged/inspected during debugging\n- Modifications don't require understanding entire expression\n- Variable names serve as documentation\n- Easier to add error handling at specific steps\n\n### When NOT to Apply\n\n- Simple transformations: `const names = users.map(u => u.name)`\n- Standard idioms: `const value = input ?? defaultValue`\n- Well-known patterns: `array.filter(Boolean)`\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3868,"content_sha256":"ff9fb3d53dd0d8e7b7438a65d07821f3bc7c95e90621883a87ef1c4a3d36023e"},{"filename":"references/flow-flatten-nesting.md","content":"---\ntitle: Flatten Deep Nesting to Maximum 2-3 Levels\nimpact: HIGH\nimpactDescription: Each nesting level beyond 2 increases cognitive load by 25% and bug probability by 15%\ntags: flow, nesting, refactoring, complexity, extraction\n---\n\n## Flatten Deep Nesting to Maximum 2-3 Levels\n\nCode nested beyond 2-3 levels becomes exponentially harder to understand. Each level requires holding more context in working memory. When you find yourself at 4+ levels, it's a signal to extract functions, use early returns, or restructure the logic. Flat code is maintainable code.\n\n**Incorrect (excessive nesting):**\n\n```typescript\nfunction processTransactions(accounts: Account[]) {\n for (const account of accounts) {\n if (account.isActive) {\n for (const transaction of account.transactions) {\n if (transaction.status === 'pending') {\n if (transaction.amount > 0) {\n for (const rule of account.rules) {\n if (rule.applies(transaction)) {\n if (rule.action === 'flag') {\n if (transaction.amount > rule.threshold) {\n transaction.flagged = true;\n transaction.flagReason = rule.reason;\n notifyCompliance(account, transaction);\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n**Correct (flattened with extraction and early continues):**\n\n```typescript\nfunction processTransactions(accounts: Account[]) {\n const activeAccounts = accounts.filter(a => a.isActive);\n\n for (const account of activeAccounts) {\n processPendingTransactions(account);\n }\n}\n\nfunction processPendingTransactions(account: Account) {\n const pendingTransactions = account.transactions.filter(\n t => t.status === 'pending' && t.amount > 0\n );\n\n for (const transaction of pendingTransactions) {\n applyRules(account, transaction);\n }\n}\n\nfunction applyRules(account: Account, transaction: Transaction) {\n for (const rule of account.rules) {\n if (!rule.applies(transaction)) {\n continue;\n }\n if (rule.action !== 'flag') {\n continue;\n }\n if (transaction.amount \u003c= rule.threshold) {\n continue;\n }\n\n transaction.flagged = true;\n transaction.flagReason = rule.reason;\n notifyCompliance(account, transaction);\n }\n}\n```\n\n**Incorrect (nested conditionals for validation):**\n\n```typescript\nfunction validateForm(form: FormData): ValidationResult {\n if (form.email) {\n if (isValidEmail(form.email)) {\n if (form.password) {\n if (form.password.length >= 8) {\n if (form.password === form.confirmPassword) {\n if (form.acceptedTerms) {\n return { valid: true };\n } else {\n return { valid: false, error: 'Must accept terms' };\n }\n } else {\n return { valid: false, error: 'Passwords do not match' };\n }\n } else {\n return { valid: false, error: 'Password too short' };\n }\n } else {\n return { valid: false, error: 'Password required' };\n }\n } else {\n return { valid: false, error: 'Invalid email' };\n }\n } else {\n return { valid: false, error: 'Email required' };\n }\n}\n```\n\n**Correct (flat validation chain):**\n\n```typescript\nfunction validateForm(form: FormData): ValidationResult {\n if (!form.email) {\n return { valid: false, error: 'Email required' };\n }\n if (!isValidEmail(form.email)) {\n return { valid: false, error: 'Invalid email' };\n }\n if (!form.password) {\n return { valid: false, error: 'Password required' };\n }\n if (form.password.length \u003c 8) {\n return { valid: false, error: 'Password too short' };\n }\n if (form.password !== form.confirmPassword) {\n return { valid: false, error: 'Passwords do not match' };\n }\n if (!form.acceptedTerms) {\n return { valid: false, error: 'Must accept terms' };\n }\n\n return { valid: true };\n}\n```\n\n**Incorrect (nested object traversal):**\n\n```typescript\nfunction getDeepValue(config: Config) {\n if (config) {\n if (config.settings) {\n if (config.settings.display) {\n if (config.settings.display.theme) {\n if (config.settings.display.theme.colors) {\n return config.settings.display.theme.colors.primary;\n }\n }\n }\n }\n }\n return DEFAULT_COLOR;\n}\n```\n\n**Correct (optional chaining or extraction):**\n\n```typescript\nfunction getDeepValue(config: Config) {\n return config?.settings?.display?.theme?.colors?.primary ?? DEFAULT_COLOR;\n}\n\n// Or for complex logic:\nfunction getDeepValue(config: Config) {\n const theme = getTheme(config);\n if (!theme?.colors) {\n return DEFAULT_COLOR;\n }\n return theme.colors.primary;\n}\n\nfunction getTheme(config: Config): Theme | undefined {\n return config?.settings?.display?.theme;\n}\n```\n\n### Flattening Strategies\n\n1. **Early returns/continues** - Exit the current scope ASAP\n2. **Extract helper functions** - Each handles one level of complexity\n3. **Filter before iterate** - Move conditions out of loops\n4. **Use optional chaining** - For safe property access\n5. **Use lookup tables** - Replace nested conditionals with data\n\n### Benefits\n\n- Each function fits in working memory\n- Code can be tested in smaller units\n- Easier to parallelize or optimize specific parts\n- Clearer separation of concerns\n\n### When NOT to Apply\n\n- State machines with inherent nesting\n- Parser/compiler code with recursive descent\n- When extraction would require excessive parameter passing\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5502,"content_sha256":"d81a06d737156129a48b0485ce23ca1e3fdacb641c0273e7e5d309af6241278f"},{"filename":"references/flow-guard-clauses.md","content":"---\ntitle: Use Guard Clauses for Preconditions\nimpact: HIGH\nimpactDescription: Guard clauses group all preconditions at function entry, reducing bug surface by 30-50% through fail-fast validation\ntags: flow, guards, validation, preconditions, defensive-programming\n---\n\n## Use Guard Clauses for Preconditions\n\nGuard clauses validate all preconditions at the function's entry point and exit immediately if validation fails. This pattern creates a clear contract: if execution passes the guards, all required conditions are met. Readers don't need to trace conditions through the entire function body.\n\n**Incorrect (validations scattered throughout):**\n\n```typescript\nfunction sendNotification(user: User, message: string, channel: Channel): void {\n let result;\n\n if (user && user.email) {\n if (message && message.trim().length > 0) {\n const sanitized = sanitizeMessage(message);\n\n if (channel === 'email') {\n if (user.emailVerified) {\n result = emailService.send(user.email, sanitized);\n } else {\n console.log('Email not verified');\n }\n } else if (channel === 'sms') {\n if (user.phone) {\n if (user.phoneVerified) {\n result = smsService.send(user.phone, sanitized);\n } else {\n console.log('Phone not verified');\n }\n } else {\n console.log('No phone number');\n }\n }\n } else {\n console.log('Empty message');\n }\n } else {\n console.log('Invalid user');\n }\n\n return result;\n}\n```\n\n**Correct (guard clauses at entry):**\n\n```typescript\nfunction sendNotification(user: User, message: string, channel: Channel): void {\n // Guard clauses - all preconditions checked upfront\n if (!user?.email) {\n throw new ValidationError('User must have an email address');\n }\n if (!message?.trim()) {\n throw new ValidationError('Message cannot be empty');\n }\n if (!['email', 'sms'].includes(channel)) {\n throw new ValidationError(`Invalid channel: ${channel}`);\n }\n\n const sanitized = sanitizeMessage(message);\n\n // Channel-specific guards\n if (channel === 'email') {\n if (!user.emailVerified) {\n throw new ValidationError('Email address not verified');\n }\n return emailService.send(user.email, sanitized);\n }\n\n if (channel === 'sms') {\n if (!user.phone) {\n throw new ValidationError('User must have a phone number for SMS');\n }\n if (!user.phoneVerified) {\n throw new ValidationError('Phone number not verified');\n }\n return smsService.send(user.phone, sanitized);\n }\n}\n```\n\n**Incorrect (null checks interleaved with logic):**\n\n```typescript\nfunction calculateShipping(order: Order): number {\n let shipping = 0;\n\n if (order) {\n const items = order.items;\n if (items) {\n for (const item of items) {\n if (item && item.weight) {\n shipping += item.weight * RATE_PER_KG;\n }\n }\n if (order.address) {\n if (order.address.country !== 'US') {\n shipping *= INTERNATIONAL_MULTIPLIER;\n }\n }\n }\n }\n\n return shipping;\n}\n```\n\n**Correct (guards enforce valid state):**\n\n```typescript\nfunction calculateShipping(order: Order): number {\n if (!order) {\n throw new Error('Order is required');\n }\n if (!order.items?.length) {\n throw new Error('Order must have items');\n }\n if (!order.address) {\n throw new Error('Order must have an address');\n }\n\n let shipping = 0;\n\n for (const item of order.items) {\n shipping += (item.weight ?? 0) * RATE_PER_KG;\n }\n\n if (order.address.country !== 'US') {\n shipping *= INTERNATIONAL_MULTIPLIER;\n }\n\n return shipping;\n}\n```\n\n### Benefits\n\n- Function contract is immediately visible\n- Invalid states fail fast before causing side effects\n- Core logic operates on guaranteed valid data\n- Testing is simplified - guards can be tested independently\n- Debugging is easier - failures point to specific validation\n\n### Related\n\n- See also [`flow-early-return`](flow-early-return.md) for reducing nesting with early returns in general\n\n### When NOT to Apply\n\n- When partial/graceful degradation is required (use defaults instead)\n- In hot paths where exceptions are too expensive\n- When building tolerant readers that handle malformed input\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4245,"content_sha256":"042615944d2ba1cb892c8e35b1abf05cd85f2c7f28a005b50981d9f034ae49cf"},{"filename":"references/flow-no-nested-ternaries.md","content":"---\ntitle: Never Use Nested Ternary Operators\nimpact: HIGH\nimpactDescription: Nested ternaries are 3-5x harder to parse than equivalent if/else, with error rates in code review increasing by 200%\ntags: flow, ternary, readability, conditionals, anti-pattern\n---\n\n## Never Use Nested Ternary Operators\n\nNested ternary operators create write-only code. The human brain processes branching logic linearly, but nested ternaries force simultaneous evaluation of multiple conditions. Even with formatting, the precedence and flow become ambiguous. One nested ternary can make an entire function unreadable.\n\n**Incorrect (nested ternaries):**\n\n```typescript\nfunction getStatusBadge(user: User): string {\n return user.isAdmin\n ? user.isActive\n ? 'admin-active'\n : 'admin-inactive'\n : user.isPremium\n ? user.isActive\n ? 'premium-active'\n : 'premium-inactive'\n : user.isActive\n ? 'basic-active'\n : 'basic-inactive';\n}\n```\n\n**Correct (explicit conditionals):**\n\n```typescript\nfunction getStatusBadge(user: User): string {\n const status = user.isActive ? 'active' : 'inactive';\n\n if (user.isAdmin) {\n return `admin-${status}`;\n }\n if (user.isPremium) {\n return `premium-${status}`;\n }\n return `basic-${status}`;\n}\n```\n\n**Incorrect (ternary chain for value selection):**\n\n```typescript\nconst priority = task.isUrgent\n ? task.isImportant\n ? 1\n : 2\n : task.isImportant\n ? 3\n : 4;\n```\n\n**Correct (lookup object or switch):**\n\n```typescript\nconst priorityMatrix = {\n 'urgent-important': 1,\n 'urgent-normal': 2,\n 'normal-important': 3,\n 'normal-normal': 4,\n};\n\nconst urgency = task.isUrgent ? 'urgent' : 'normal';\nconst importance = task.isImportant ? 'important' : 'normal';\nconst priority = priorityMatrix[`${urgency}-${importance}`];\n```\n\n**Incorrect (inline nested ternary in JSX):**\n\n```tsx\nfunction UserAvatar({ user }: Props) {\n return (\n \u003cdiv className={\n user.status === 'online'\n ? user.isPremium\n ? 'avatar-premium-online'\n : 'avatar-online'\n : user.status === 'away'\n ? 'avatar-away'\n : 'avatar-offline'\n }>\n {user.name}\n \u003c/div>\n );\n}\n```\n\n**Correct (helper function with clear logic):**\n\n```tsx\nfunction getAvatarClass(user: User): string {\n if (user.status === 'online') {\n return user.isPremium ? 'avatar-premium-online' : 'avatar-online';\n }\n if (user.status === 'away') {\n return 'avatar-away';\n }\n return 'avatar-offline';\n}\n\nfunction UserAvatar({ user }: Props) {\n return (\n \u003cdiv className={getAvatarClass(user)}>\n {user.name}\n \u003c/div>\n );\n}\n```\n\n### Acceptable Single-Level Ternary\n\n```typescript\n// OK: Single ternary for simple binary choice\nconst label = isLoading ? 'Loading...' : 'Submit';\n\n// OK: Nullish coalescing or optional chaining\nconst name = user?.name ?? 'Anonymous';\n\n// NOT OK: Even two levels is too much\nconst label = isLoading ? 'Loading...' : isDisabled ? 'Disabled' : 'Submit';\n```\n\n### Benefits\n\n- Code flow is immediately apparent\n- Debugging is possible (can set breakpoints)\n- Modifications don't require understanding entire expression\n- Code review can focus on logic, not parsing\n\n### When NOT to Apply\n\n- Single-level ternaries for simple binary choices are acceptable\n- Ternaries inside template literals for simple value selection\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3343,"content_sha256":"33256dfa0a2361d661b477dd583846e854da4e93e741566194a57ee356d42527"},{"filename":"references/flow-optional-chaining.md","content":"---\ntitle: Use Optional Chaining and Nullish Coalescing\nimpact: HIGH\nimpactDescription: Replaces 3-8 lines of null-checking boilerplate with a single expression, reducing nesting by 2-4 levels\ntags: flow, optional-chaining, nullish-coalescing, null-checks\n---\n\n## Use Optional Chaining and Nullish Coalescing\n\nDeep null-checking creates pyramids of `if` statements that obscure the actual logic. Optional chaining (`?.`) and nullish coalescing (`??`) collapse these checks into readable expressions that clearly show the intent: \"get this value, or use a fallback.\"\n\n**Incorrect (nested null checks):**\n\n```typescript\nfunction getUserCity(user: User | null): string {\n if (user) {\n if (user.address) {\n if (user.address.city) {\n return user.address.city;\n }\n }\n }\n return 'Unknown';\n}\n\nfunction getDisplayName(profile: Profile | null): string {\n let displayName = 'Anonymous';\n if (profile !== null && profile !== undefined) {\n if (profile.nickname !== null && profile.nickname !== undefined) {\n displayName = profile.nickname;\n } else if (profile.firstName !== null && profile.firstName !== undefined) {\n displayName = profile.firstName;\n }\n }\n return displayName;\n}\n```\n\n**Correct (optional chaining and nullish coalescing):**\n\n```typescript\nfunction getUserCity(user: User | null): string {\n return user?.address?.city ?? 'Unknown';\n}\n\nfunction getDisplayName(profile: Profile | null): string {\n return profile?.nickname ?? profile?.firstName ?? 'Anonymous';\n}\n```\n\n**Incorrect (Python - verbose None checks):**\n\n```python\ndef get_config_value(config, section, key, default=None):\n if config is not None:\n section_data = config.get(section)\n if section_data is not None:\n value = section_data.get(key)\n if value is not None:\n return value\n return default\n```\n\n**Correct (Python - dictionary chaining):**\n\n```python\ndef get_config_value(config, section, key, default=None):\n if config is None:\n return default\n return config.get(section, {}).get(key, default)\n```\n\n### When NOT to Apply\n\n- When you need to distinguish between `null`, `undefined`, and `false`/`0`/`''` (use explicit checks)\n- When each null check has different error handling or logging\n- When the falsy-value semantics of `||` are intentionally different from `??`\n\n### Benefits\n\n- Eliminates 3-8 lines of null-checking per access chain\n- Reduces nesting by 2-4 levels\n- Intent is immediately clear: \"access this path or use default\"\n- Fewer intermediate variables needed\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2563,"content_sha256":"fa150766601fa559d8ea1d86f7e189e99b7095f1119c8a3d2d2871ee9859c81d"},{"filename":"references/flow-positive-conditions.md","content":"---\ntitle: Prefer Positive Conditions Over Double Negatives\nimpact: HIGH\nimpactDescription: Positive conditions reduce cognitive parsing time by 30-40% and cut logical errors in boolean expressions by 25%\ntags: flow, conditions, boolean, readability, naming\n---\n\n## Prefer Positive Conditions Over Double Negatives\n\nThe human brain processes positive statements faster than negative ones. Double negatives require mental inversion that slows comprehension and increases error rates. Write conditions that state what IS true, not what ISN'T NOT true.\n\n**Incorrect (double negatives):**\n\n```typescript\nif (!user.isNotVerified) {\n sendWelcomeEmail(user);\n}\n\nif (!isNotEmpty(list)) {\n return 'No items';\n}\n\nif (!config.disableCache !== false) {\n useCache();\n}\n\nconst cannotProceed = !isValid || !hasPermission;\nif (!cannotProceed) {\n proceed();\n}\n```\n\n**Correct (positive conditions):**\n\n```typescript\nif (user.isVerified) {\n sendWelcomeEmail(user);\n}\n\nif (isEmpty(list)) {\n return 'No items';\n}\n\nif (config.enableCache) {\n useCache();\n}\n\nconst canProceed = isValid && hasPermission;\nif (canProceed) {\n proceed();\n}\n```\n\n**Incorrect (negative function names):**\n\n```typescript\nfunction isNotAdmin(user: User): boolean {\n return user.role !== 'admin';\n}\n\nfunction hasNoErrors(result: Result): boolean {\n return result.errors.length === 0;\n}\n\nfunction isDisabled(feature: Feature): boolean {\n return !feature.enabled;\n}\n\n// Usage becomes confusing\nif (!isNotAdmin(user) && !isDisabled(feature)) {\n showAdminPanel();\n}\n```\n\n**Correct (positive function names):**\n\n```typescript\nfunction isAdmin(user: User): boolean {\n return user.role === 'admin';\n}\n\nfunction isValid(result: Result): boolean {\n return result.errors.length === 0;\n}\n\nfunction isEnabled(feature: Feature): boolean {\n return feature.enabled;\n}\n\n// Usage is clear\nif (isAdmin(user) && isEnabled(feature)) {\n showAdminPanel();\n}\n```\n\n**Incorrect (negative variable names):**\n\n```typescript\nconst notFound = items.indexOf(target) === -1;\nif (!notFound) {\n processItem(target);\n}\n\nconst isInvalid = !schema.validate(data);\nif (!isInvalid) {\n save(data);\n}\n\nlet hideModal = true;\nif (!hideModal) {\n modal.show();\n}\n```\n\n**Correct (positive variable names):**\n\n```typescript\nconst found = items.indexOf(target) !== -1;\nif (found) {\n processItem(target);\n}\n\n// Or even better with includes:\nif (items.includes(target)) {\n processItem(target);\n}\n\nconst isValid = schema.validate(data);\nif (isValid) {\n save(data);\n}\n\nlet showModal = false;\nif (showModal) {\n modal.show();\n}\n```\n\n**Incorrect (confusing boolean logic):**\n\n```typescript\n// What does this even mean?\nif (!(user.inactive || !user.emailConfirmed) && !config.skipValidation) {\n allowAccess();\n}\n```\n\n**Correct (clear positive logic):**\n\n```typescript\nconst isActiveUser = !user.inactive;\nconst hasConfirmedEmail = user.emailConfirmed;\nconst shouldValidate = !config.skipValidation;\n\nif (isActiveUser && hasConfirmedEmail && shouldValidate) {\n allowAccess();\n}\n\n// Or extract to a well-named function\nfunction canAccessSystem(user: User, config: Config): boolean {\n const isActiveUser = !user.inactive;\n const hasConfirmedEmail = user.emailConfirmed;\n const requiresValidation = !config.skipValidation;\n\n return isActiveUser && hasConfirmedEmail && requiresValidation;\n}\n```\n\n### Refactoring Patterns\n\n| Negative Form | Positive Form |\n|--------------|---------------|\n| `!isNotValid` | `isValid` |\n| `!isEmpty` | `hasItems` |\n| `!isDisabled` | `isEnabled` |\n| `notFound === false` | `found === true` or just `found` |\n| `!user.inactive` | `user.isActive` (may need data change) |\n| `errors.length === 0` | `isValid` or `hasNoErrors` |\n\n### Benefits\n\n- Conditions read like natural language\n- Fewer mental inversions when reading\n- Reduced chance of logic errors\n- Easier to combine conditions with && and ||\n- Self-documenting variable and function names\n\n### When NOT to Apply\n\n- When the negative is the natural domain concept (e.g., `isDeprecated`, `wasDeleted`)\n- When matching an external API that uses negative naming\n- In guard clauses where `if (!x) return` is idiomatic\n- When `!condition` is clearer than creating a new named positive\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4186,"content_sha256":"59dfcffdbcc70495e6ea9d14020ed495ebb039a5111c2d9e17360a79fab5a921"},{"filename":"references/flow-single-responsibility.md","content":"---\ntitle: Each Code Block Should Do One Thing\nimpact: HIGH\nimpactDescription: Single-responsibility blocks are 60% faster to understand and 40% less likely to introduce bugs when modified\ntags: flow, single-responsibility, cohesion, blocks, functions\n---\n\n## Each Code Block Should Do One Thing\n\nWhen a code block (function, loop, conditional branch) tries to do multiple things, it becomes harder to name, test, and modify. Each block should have one clear purpose. If you can't describe what a block does without using \"and\", split it up.\n\n**Incorrect (loop doing multiple things):**\n\n```typescript\nfunction processOrders(orders: Order[]) {\n let totalRevenue = 0;\n const flaggedOrders: Order[] = [];\n const customerOrderCounts: Map\u003cstring, number> = new Map();\n const emailsToSend: Email[] = [];\n\n for (const order of orders) {\n // Calculate revenue\n totalRevenue += order.total;\n\n // Flag suspicious orders\n if (order.total > 10000 || order.items.length > 50) {\n flaggedOrders.push(order);\n }\n\n // Count orders per customer\n const count = customerOrderCounts.get(order.customerId) || 0;\n customerOrderCounts.set(order.customerId, count + 1);\n\n // Prepare confirmation emails\n if (order.status === 'completed') {\n emailsToSend.push({\n to: order.customerEmail,\n subject: 'Order Confirmed',\n body: generateOrderEmail(order),\n });\n }\n\n // Update inventory\n for (const item of order.items) {\n inventory.decrement(item.sku, item.quantity);\n }\n }\n\n return { totalRevenue, flaggedOrders, customerOrderCounts, emailsToSend };\n}\n```\n\n**Correct (separate single-purpose functions):**\n\n```typescript\nfunction processOrders(orders: Order[]): ProcessingResult {\n return {\n totalRevenue: calculateTotalRevenue(orders),\n flaggedOrders: findSuspiciousOrders(orders),\n customerOrderCounts: countOrdersByCustomer(orders),\n emailsToSend: prepareConfirmationEmails(orders),\n };\n}\n\nfunction calculateTotalRevenue(orders: Order[]): number {\n return orders.reduce((sum, order) => sum + order.total, 0);\n}\n\nfunction findSuspiciousOrders(orders: Order[]): Order[] {\n return orders.filter(\n order => order.total > 10000 || order.items.length > 50\n );\n}\n\nfunction countOrdersByCustomer(orders: Order[]): Map\u003cstring, number> {\n const counts = new Map\u003cstring, number>();\n for (const order of orders) {\n const current = counts.get(order.customerId) || 0;\n counts.set(order.customerId, current + 1);\n }\n return counts;\n}\n\nfunction prepareConfirmationEmails(orders: Order[]): Email[] {\n return orders\n .filter(order => order.status === 'completed')\n .map(order => ({\n to: order.customerEmail,\n subject: 'Order Confirmed',\n body: generateOrderEmail(order),\n }));\n}\n\nfunction updateInventory(orders: Order[]): void {\n for (const order of orders) {\n for (const item of order.items) {\n inventory.decrement(item.sku, item.quantity);\n }\n }\n}\n```\n\n**Incorrect (function with multiple responsibilities):**\n\n```typescript\nasync function handleUserSignup(data: SignupData) {\n // Validate\n if (!data.email || !isValidEmail(data.email)) {\n throw new Error('Invalid email');\n }\n if (!data.password || data.password.length \u003c 8) {\n throw new Error('Password too short');\n }\n\n // Check existing\n const existing = await db.users.findByEmail(data.email);\n if (existing) {\n throw new Error('Email already registered');\n }\n\n // Hash password\n const salt = await bcrypt.genSalt(10);\n const hashedPassword = await bcrypt.hash(data.password, salt);\n\n // Create user\n const user = await db.users.create({\n email: data.email,\n password: hashedPassword,\n createdAt: new Date(),\n });\n\n // Send welcome email\n await emailService.send({\n to: user.email,\n template: 'welcome',\n data: { name: user.name },\n });\n\n // Create audit log\n await auditLog.record({\n action: 'user_signup',\n userId: user.id,\n timestamp: new Date(),\n });\n\n // Initialize settings\n await db.userSettings.create({\n userId: user.id,\n theme: 'light',\n notifications: true,\n });\n\n return user;\n}\n```\n\n**Correct (orchestrator with single-purpose helpers):**\n\n```typescript\nasync function handleUserSignup(data: SignupData): Promise\u003cUser> {\n validateSignupData(data);\n await ensureEmailNotTaken(data.email);\n\n const user = await createUser(data);\n\n await sendWelcomeEmail(user);\n await recordSignupAudit(user);\n await initializeUserSettings(user);\n\n return user;\n}\n\nfunction validateSignupData(data: SignupData): void {\n if (!data.email || !isValidEmail(data.email)) {\n throw new ValidationError('Invalid email');\n }\n if (!data.password || data.password.length \u003c 8) {\n throw new ValidationError('Password must be at least 8 characters');\n }\n}\n\nasync function ensureEmailNotTaken(email: string): Promise\u003cvoid> {\n const existing = await db.users.findByEmail(email);\n if (existing) {\n throw new ConflictError('Email already registered');\n }\n}\n\nasync function createUser(data: SignupData): Promise\u003cUser> {\n const hashedPassword = await hashPassword(data.password);\n return db.users.create({\n email: data.email,\n password: hashedPassword,\n createdAt: new Date(),\n });\n}\n\nasync function hashPassword(password: string): Promise\u003cstring> {\n const salt = await bcrypt.genSalt(10);\n return bcrypt.hash(password, salt);\n}\n```\n\n### Signs a Block Does Too Much\n\n- Name includes \"and\" or describes multiple actions\n- Multiple unrelated variables being modified\n- Comments separating different \"sections\"\n- Difficult to write a focused unit test\n- Changes to one part risk breaking another\n\n### Benefits\n\n- Each piece can be tested in isolation\n- Functions can be reused in different contexts\n- Changes are localized - modify one thing without risking others\n- Names become self-documenting\n- Easier to parallelize independent operations\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5894,"content_sha256":"faf94edb531f7af90d1ff032e3cf1a65ab5d5ec05b335072cec7f33831dd27a6"},{"filename":"references/idiom-go-error-handling.md","content":"---\ntitle: Handle Errors Immediately After the Call\nimpact: LOW-MEDIUM\nimpactDescription: Prevents error masking, ensures 100% of error paths are explicitly handled\ntags: idiom, go, error-handling, explicit-errors\n---\n\n## Handle Errors Immediately After the Call\n\nGo's explicit error handling is a feature, not a burden. Always check errors immediately after a function call returns—don't defer error checks or accumulate them. This pattern makes control flow explicit and ensures errors are handled in context where you have the most information.\n\n**Incorrect (deferred or accumulated error checking):**\n\n```go\n// Bad: errors accumulate, hard to know which failed\nfunc processFiles(paths []string) error {\n var lastErr error\n\n for _, path := range paths {\n data, err := os.ReadFile(path)\n if err != nil {\n lastErr = err // Previous errors lost\n }\n\n result, err := process(data)\n if err != nil {\n lastErr = err\n }\n\n err = save(result)\n if err != nil {\n lastErr = err\n }\n }\n\n return lastErr\n}\n\n// Bad: ignoring error\nfunc quickRead(path string) []byte {\n data, _ := os.ReadFile(path) // Silent failure\n return data\n}\n```\n\n**Correct (handle immediately with context):**\n\n```go\nfunc processFiles(paths []string) error {\n for _, path := range paths {\n data, err := os.ReadFile(path)\n if err != nil {\n return fmt.Errorf(\"reading %s: %w\", path, err)\n }\n\n result, err := process(data)\n if err != nil {\n return fmt.Errorf(\"processing %s: %w\", path, err)\n }\n\n if err := save(result); err != nil {\n return fmt.Errorf(\"saving result for %s: %w\", path, err)\n }\n }\n\n return nil\n}\n\n// When you need to continue despite errors, collect them explicitly\nfunc processAllFiles(paths []string) error {\n var errs []error\n\n for _, path := range paths {\n if err := processFile(path); err != nil {\n errs = append(errs, fmt.Errorf(\"%s: %w\", path, err))\n continue // Explicit decision to continue\n }\n }\n\n return errors.Join(errs...) // Go 1.20+\n}\n```\n\n### Wrapping Errors for Context\n\n```go\n// Always add context when propagating\nfunc LoadConfig(path string) (*Config, error) {\n data, err := os.ReadFile(path)\n if err != nil {\n return nil, fmt.Errorf(\"load config: %w\", err)\n }\n\n var cfg Config\n if err := json.Unmarshal(data, &cfg); err != nil {\n return nil, fmt.Errorf(\"parse config %s: %w\", path, err)\n }\n\n return &cfg, nil\n}\n```\n\n### When Ignoring Errors is Acceptable\n\n```go\n// Explicitly document why it's safe to ignore\n_ = writer.Close() // Best effort cleanup, already returning another error\n\n// Or use a helper for intentional ignores\nfunc must[T any](v T, err error) T {\n if err != nil {\n panic(err)\n }\n return v\n}\n```\n\n### Benefits\n\n- Errors handled with full context available\n- Control flow is explicit and linear\n- Error wrapping builds informative stack traces\n- No hidden failures or silent data corruption\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3112,"content_sha256":"dae7abf6b9640480dfad21f02d5c9aa4aa9cd250d6b92c2021c040ff80d39cec"},{"filename":"references/idiom-prefer-language-builtins.md","content":"---\ntitle: Prefer Language and Standard Library Builtins\nimpact: LOW-MEDIUM\nimpactDescription: Reduces code by 20-40%, eliminates bugs from manual reimplementations\ntags: idiom, all-languages, stdlib, builtins\n---\n\n## Prefer Language and Standard Library Builtins\n\nEvery language provides optimized, well-tested utilities for common operations. Manual implementations are almost always buggier, slower, and harder to maintain. Before writing utility code, check if the language or standard library already provides it.\n\n**Incorrect (manual implementations):**\n\n```typescript\n// TypeScript: Manual array operations\nfunction unique\u003cT>(arr: T[]): T[] {\n const seen = new Set\u003cT>();\n const result: T[] = [];\n for (const item of arr) {\n if (!seen.has(item)) {\n seen.add(item);\n result.push(item);\n }\n }\n return result;\n}\n\nfunction groupBy\u003cT>(arr: T[], key: keyof T): Record\u003cstring, T[]> {\n const result: Record\u003cstring, T[]> = {};\n for (const item of arr) {\n const k = String(item[key]);\n if (!result[k]) result[k] = [];\n result[k].push(item);\n }\n return result;\n}\n```\n\n**Correct (use builtins):**\n\n```typescript\n// TypeScript: Use Set and Object.groupBy (ES2024)\nconst uniqueItems = [...new Set(arr)];\nconst grouped = Object.groupBy(arr, item => item.category);\n```\n\n**Incorrect (Python manual operations):**\n\n```python\n# Python: Manual implementations\ndef flatten(nested_list):\n result = []\n for sublist in nested_list:\n for item in sublist:\n result.append(item)\n return result\n\ndef find_max_by_key(items, key_func):\n max_item = None\n max_val = float('-inf')\n for item in items:\n val = key_func(item)\n if val > max_val:\n max_val = val\n max_item = item\n return max_item\n```\n\n**Correct (Python stdlib):**\n\n```python\n# Python: Use itertools and builtins\nfrom itertools import chain\n\nflattened = list(chain.from_iterable(nested_list))\nmax_item = max(items, key=key_func)\n\n# Other commonly overlooked builtins\nfrom collections import Counter, defaultdict\nfrom functools import lru_cache, reduce\nfrom pathlib import Path # Instead of os.path string manipulation\n```\n\n**Incorrect (Go manual operations):**\n\n```go\n// Go: Manual slice operations\nfunc contains(slice []string, item string) bool {\n for _, s := range slice {\n if s == item {\n return true\n }\n }\n return false\n}\n\nfunc min(a, b int) int {\n if a \u003c b {\n return a\n }\n return b\n}\n```\n\n**Correct (Go stdlib and generics):**\n\n```go\n// Go 1.21+: Use slices and cmp packages\nimport (\n \"slices\"\n \"cmp\"\n)\n\nfound := slices.Contains(slice, item)\nminimum := min(a, b) // builtin since Go 1.21\nslices.SortFunc(items, func(a, b Item) int {\n return cmp.Compare(a.Priority, b.Priority)\n})\n```\n\n**Incorrect (Rust manual operations):**\n\n```rust\n// Rust: Manual implementations\nfn join_strings(strings: &[String], sep: &str) -> String {\n let mut result = String::new();\n for (i, s) in strings.iter().enumerate() {\n if i > 0 {\n result.push_str(sep);\n }\n result.push_str(s);\n }\n result\n}\n```\n\n**Correct (Rust stdlib):**\n\n```rust\n// Rust: Use standard library\nlet joined = strings.join(\", \");\n\n// Other commonly overlooked std features\nuse std::collections::HashMap;\nlet counts: HashMap\u003c_, _> = items.iter().fold(HashMap::new(), |mut acc, x| {\n *acc.entry(x).or_insert(0) += 1;\n acc\n});\n// Or use itertools crate for more complex operations\n```\n\n### Common Builtins to Know\n\n| Operation | TypeScript | Python | Go | Rust |\n|-----------|------------|--------|-----|------|\n| Unique | `new Set()` | `set()` | `slices.Compact` | `.dedup()` |\n| Sort | `.sort()` | `sorted()` | `slices.Sort` | `.sort()` |\n| Find | `.find()` | `next(x for...)` | `slices.Index` | `.find()` |\n| Group | `Object.groupBy` | `itertools.groupby` | manual/lo | `.group_by()` |\n| Flatten | `.flat()` | `chain.from_iterable` | manual | `.flatten()` |\n\n### Benefits\n\n- Battle-tested implementations with edge cases handled\n- Often optimized at the language/runtime level\n- Familiar to other developers reading your code\n- Reduces maintenance burden and potential bugs\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4181,"content_sha256":"ddf07768d0b600b23ca641cbb8a017236d8f6cad4a3df70589d73ee82acc5405"},{"filename":"references/idiom-python-comprehensions.md","content":"---\ntitle: Use Comprehensions for Simple Transforms\nimpact: LOW-MEDIUM\nimpactDescription: Comprehensions are 10-30% faster and more readable for simple cases\ntags: idiom, python, comprehensions, readability\n---\n\n## Use Comprehensions for Simple Transforms\n\nPython comprehensions (list, dict, set, generator) are idiomatic for simple transformations and filtering. They're more concise and often faster than equivalent loops. However, complex comprehensions with multiple conditions or nested logic become unreadable—use regular loops instead.\n\n**Incorrect (loop for simple transform):**\n\n```python\n# Verbose for a simple operation\nresult = []\nfor user in users:\n if user.is_active:\n result.append(user.email)\n\n# Building dict inefficiently\nlookup = {}\nfor item in items:\n lookup[item.id] = item.name\n```\n\n**Correct (comprehension for simple transform):**\n\n```python\n# Clear and Pythonic\nresult = [user.email for user in users if user.is_active]\n\n# Dict comprehension\nlookup = {item.id: item.name for item in items}\n\n# Set comprehension for unique values\nunique_categories = {product.category for product in products}\n\n# Generator for memory efficiency with large data\ntotal = sum(order.amount for order in orders if order.status == \"completed\")\n```\n\n**Incorrect (complex comprehension hurts readability):**\n\n```python\n# Too complex - multiple conditions and transformations\nresult = [\n transform_data(item.value)\n for category in categories\n for item in category.items\n if item.is_valid and item.value > threshold\n if not item.is_deleted\n]\n```\n\n**Correct (loop for complex logic):**\n\n```python\n# Clear with explicit logic\nresult = []\nfor category in categories:\n for item in category.items:\n if not item.is_valid or item.is_deleted:\n continue\n if item.value \u003c= threshold:\n continue\n result.append(transform_data(item.value))\n```\n\n### Guidelines\n\n| Use Comprehensions | Use Loops |\n|-------------------|-----------|\n| Single filter + map | Multiple conditions |\n| One level of nesting | Side effects needed |\n| Fits on one line (~80 chars) | Complex transformations |\n| Pure data transformation | Exception handling required |\n\n### Walrus Operator in Comprehensions (Python 3.8+)\n\n```python\n# Avoid repeated computation\nresults = [y for x in data if (y := expensive_transform(x)) is not None]\n```\n\n### Benefits\n\n- More readable for simple cases\n- Often 10-30% faster than equivalent loops\n- Generator expressions avoid building intermediate lists\n- Clearly signals \"this is a data transformation\"\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2572,"content_sha256":"8ec23fc39f21c6a04982b12316f942e519771411f083f3fc354ba10058786427"},{"filename":"references/idiom-rust-iterator-chains.md","content":"---\ntitle: Use Iterator Chains When Clearer Than Loops\nimpact: LOW-MEDIUM\nimpactDescription: Can reduce code by 30-50% for transforms, but overuse hurts readability\ntags: idiom, rust, iterators, functional\n---\n\n## Use Iterator Chains When Clearer Than Loops\n\nRust's iterator combinators (`map`, `filter`, `fold`, etc.) can express data transformations more declaratively than loops. However, they're not always clearer—complex chains with multiple closures or stateful operations often become harder to understand than equivalent loops. Choose based on readability, not style preference.\n\n**Incorrect (forced iterator chain hurts clarity):**\n\n```rust\n// Too complex - hard to follow the logic\nfn process_orders(orders: &[Order]) -> HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> {\n orders\n .iter()\n .filter(|o| o.status == Status::Pending)\n .filter_map(|o| {\n if let Some(customer) = get_customer(o.customer_id) {\n Some((customer, o))\n } else {\n log::warn!(\"Unknown customer: {}\", o.customer_id);\n None\n }\n })\n .map(|(customer, order)| {\n let processed = process_single_order(order, &customer);\n (customer.id, processed)\n })\n .fold(HashMap::new(), |mut acc, (id, order)| {\n acc.entry(id).or_default().push(order);\n acc\n })\n}\n```\n\n**Correct (loop is clearer for complex logic):**\n\n```rust\nfn process_orders(orders: &[Order]) -> HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> {\n let mut result: HashMap\u003cCustomerId, Vec\u003cProcessedOrder>> = HashMap::new();\n\n for order in orders.iter().filter(|o| o.status == Status::Pending) {\n let Some(customer) = get_customer(order.customer_id) else {\n log::warn!(\"Unknown customer: {}\", order.customer_id);\n continue;\n };\n\n let processed = process_single_order(order, &customer);\n result.entry(customer.id).or_default().push(processed);\n }\n\n result\n}\n```\n\n**Correct (iterator chain for simple transforms):**\n\n```rust\n// Clear and concise - good use of iterators\nfn get_active_user_emails(users: &[User]) -> Vec\u003cString> {\n users\n .iter()\n .filter(|u| u.is_active)\n .map(|u| u.email.clone())\n .collect()\n}\n\n// Sum with filter - straightforward\nfn total_revenue(orders: &[Order]) -> Decimal {\n orders\n .iter()\n .filter(|o| o.status == Status::Completed)\n .map(|o| o.total)\n .sum()\n}\n```\n\n### Guidelines\n\n| Use Iterators When | Use Loops When |\n|-------------------|----------------|\n| Simple filter/map/collect | Multiple related mutations |\n| No side effects needed | Early returns with context |\n| Each step is self-contained | Stateful iteration |\n| 2-3 combinators max | Complex branching logic |\n\n### Benefits of Knowing Both\n\n- Iterator chains can be lazy and more memory-efficient\n- Loops are easier to debug with breakpoints\n- Mixing both (filter in iterator, logic in loop) often optimal\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3022,"content_sha256":"8d66ef353819631457ebe676645bfee795cee9ad4f838947e2c6380ed8344686"},{"filename":"references/idiom-rust-question-mark.md","content":"---\ntitle: Use ? for Error Propagation\nimpact: LOW-MEDIUM\nimpactDescription: Reduces error handling boilerplate by 60-70%, improves readability\ntags: idiom, rust, error-handling, question-mark-operator\n---\n\n## Use ? for Error Propagation\n\nThe `?` operator is Rust's idiomatic way to propagate errors up the call stack. It replaces verbose nested `match` statements with a concise syntax that makes the happy path obvious while still handling errors explicitly. This is central to Rust's philosophy of making error handling visible but not burdensome.\n\n**Incorrect (nested match statements obscure logic):**\n\n```rust\nfn read_config(path: &str) -> Result\u003cConfig, ConfigError> {\n let file = match File::open(path) {\n Ok(f) => f,\n Err(e) => return Err(ConfigError::IoError(e)),\n };\n\n let mut contents = String::new();\n match file.read_to_string(&mut contents) {\n Ok(_) => {},\n Err(e) => return Err(ConfigError::IoError(e)),\n };\n\n match serde_json::from_str(&contents) {\n Ok(config) => Ok(config),\n Err(e) => Err(ConfigError::ParseError(e)),\n }\n}\n```\n\n**Correct (? operator for clean propagation):**\n\n```rust\nfn read_config(path: &str) -> Result\u003cConfig, ConfigError> {\n let mut file = File::open(path)?;\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n let config = serde_json::from_str(&contents)?;\n Ok(config)\n}\n\n// Even cleaner with method chaining\nfn read_config_chained(path: &str) -> Result\u003cConfig, ConfigError> {\n let contents = std::fs::read_to_string(path)?;\n Ok(serde_json::from_str(&contents)?)\n}\n```\n\n### When to Use match Instead\n\n- When you need to handle specific error variants differently\n- When you want to add context or transform the error\n- When recovery is possible and you don't want to propagate\n\n```rust\n// match is appropriate here - different handling per error\nfn connect_with_retry(addr: &str) -> Result\u003cConnection, Error> {\n match TcpStream::connect(addr) {\n Ok(stream) => Ok(Connection::new(stream)),\n Err(e) if e.kind() == ErrorKind::ConnectionRefused => {\n thread::sleep(Duration::from_secs(1));\n connect_with_retry(addr) // Retry on refused\n }\n Err(e) => Err(e.into()), // Propagate other errors\n }\n}\n```\n\n### Benefits\n\n- Happy path is immediately visible\n- Error propagation is explicit but concise\n- Works with both `Result` and `Option` types\n- Combines well with `From` trait for automatic error conversion\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2505,"content_sha256":"bbcb6bbe3f68f118179b4c85bfe49f4b47e6f1b982f8e13522fceae51e8255d6"},{"filename":"references/idiom-ts-const-assertions.md","content":"---\ntitle: Use const Assertions and readonly for Immutability\nimpact: LOW-MEDIUM\nimpactDescription: Prevents accidental mutations, enables 10-20% better type inference for literals\ntags: idiom, typescript, immutability, const-assertions\n---\n\n## Use const Assertions and readonly for Immutability\n\nConst assertions (`as const`) and `readonly` modifiers signal intent and prevent accidental mutations. They also enable TypeScript to infer literal types instead of widened types, which improves type safety and enables better autocomplete.\n\n**Incorrect (mutable by default, widened types):**\n\n```typescript\n// Type is string[], not readonly [\"admin\", \"user\", \"guest\"]\nconst ROLES = [\"admin\", \"user\", \"guest\"];\n\n// Type is { status: string; code: number }, loses literal info\nconst ERROR_CODES = {\n NOT_FOUND: { status: \"not_found\", code: 404 },\n FORBIDDEN: { status: \"forbidden\", code: 403 },\n};\n\n// Can be accidentally mutated\nfunction processItems(items: string[]) {\n items.push(\"extra\"); // Mutates original array\n return items.sort();\n}\n```\n\n**Correct (immutable with precise types):**\n\n```typescript\n// Type is readonly [\"admin\", \"user\", \"guest\"]\nconst ROLES = [\"admin\", \"user\", \"guest\"] as const;\ntype Role = typeof ROLES[number]; // \"admin\" | \"user\" | \"guest\"\n\n// Type preserves literal values\nconst ERROR_CODES = {\n NOT_FOUND: { status: \"not_found\", code: 404 },\n FORBIDDEN: { status: \"forbidden\", code: 403 },\n} as const;\ntype ErrorStatus = typeof ERROR_CODES[keyof typeof ERROR_CODES][\"status\"];\n\n// Signals no mutation, creates new array\nfunction processItems(items: readonly string[]): string[] {\n return [...items, \"extra\"].sort();\n}\n```\n\n### When NOT to Use\n\n- Arrays or objects that genuinely need mutation for performance\n- Loop counters and accumulator variables\n- Builder patterns that rely on mutation\n\n### Benefits\n\n- Literal type inference enables exhaustive switch checks\n- `readonly` in function parameters documents non-mutation\n- Catches accidental `.push()`, `.pop()`, assignment at compile time\n- Enables deriving union types from const arrays/objects\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2083,"content_sha256":"568c44e59149004c34c98e6218816992128169f7b0a02a67a9ab16fa19d14c2f"},{"filename":"references/idiom-ts-strict-types.md","content":"---\ntitle: Use Strict Types Over any\nimpact: LOW-MEDIUM\nimpactDescription: Catches 15-30% more type errors at compile time, reduces runtime debugging\ntags: idiom, typescript, type-safety, strict-mode\n---\n\n## Use Strict Types Over any\n\nUsing `any` defeats TypeScript's purpose and hides bugs that would otherwise be caught at compile time. Prefer `unknown` with type narrowing when the type is truly uncertain—this forces explicit type checking before use, making your code both safer and more self-documenting.\n\n**Incorrect (using any bypasses type checking):**\n\n```typescript\nfunction parseUserPayload(payload: any) {\n // No type safety - runtime errors possible\n return payload.items.map((item: any) => item.name.toUpperCase());\n}\n\nfunction parseApiResponse(response: any): any {\n return JSON.parse(response.body);\n}\n```\n\n**Correct (using unknown with narrowing):**\n\n```typescript\ninterface UserPayload {\n items: Array\u003c{ name: string }>;\n}\n\nfunction isUserPayload(data: unknown): data is UserPayload {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'items' in data &&\n Array.isArray((data as UserPayload).items)\n );\n}\n\nfunction parseUserPayload(data: unknown): string[] {\n if (!isUserPayload(data)) {\n throw new Error('Invalid user payload structure');\n }\n return data.items.map(item => item.name.toUpperCase());\n}\n\ninterface ApiResponse {\n body: string;\n}\n\nfunction parseApiResponse(response: ApiResponse): unknown {\n return JSON.parse(response.body);\n}\n```\n\n### When to Allow any\n\n- Legacy code migration where full typing isn't feasible yet\n- Third-party libraries without type definitions (prefer `@types/*` packages)\n- Explicit `// eslint-disable-next-line @typescript-eslint/no-explicit-any` with justification\n\n### Benefits\n\n- Compiler catches type mismatches before runtime\n- IDE autocomplete works correctly\n- Refactoring becomes safer with full type coverage\n- Self-documenting code through explicit type contracts\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":1966,"content_sha256":"7692727da16c6682616477c9be3d50e6fbd0a1ae0cd48bbb80b9e09e71b9c3fb"},{"filename":"references/name-avoid-abbreviations.md","content":"---\ntitle: Avoid Cryptic Abbreviations\nimpact: MEDIUM-HIGH\nimpactDescription: Full words reduce misinterpretation risk and eliminate the 5-10 seconds developers spend deciphering each abbreviation\ntags: name, readability, abbreviations, clarity, onboarding\n---\n\n## Avoid Cryptic Abbreviations\n\nAbbreviations save a few keystrokes but cost readers significant mental effort to decode. What seems obvious to the author (who just created the abbreviation) becomes a puzzle for future readers. Use complete words that anyone can understand without context clues or tribal knowledge.\n\n**Incorrect (cryptic abbreviations):**\n\n```typescript\n// Bad: What do these mean?\nconst usrMgr = new UserManager();\nconst cfg = loadConfig();\nconst txn = db.beginTransaction();\nconst btn = document.getElementById('submit');\nconst req = new HttpRequest();\nconst res = await fetch(url);\nconst err = validate(input);\nconst intrm = calculateIntermediate();\nconst cnt = items.length;\nconst idx = findPosition(target);\nconst ctx = createContext();\nconst val = getValue();\nconst cb = () => console.log('done');\n```\n\n**Correct (full words):**\n\n```typescript\n// Good: immediately understandable\nconst userManager = new UserManager();\nconst configuration = loadConfig();\nconst transaction = db.beginTransaction();\nconst submitButton = document.getElementById('submit');\nconst httpRequest = new HttpRequest();\nconst response = await fetch(url);\nconst validationError = validate(input);\nconst intermediateResult = calculateIntermediate();\nconst itemCount = items.length;\nconst targetIndex = findPosition(target);\nconst requestContext = createContext();\nconst currentValue = getValue();\nconst onComplete = () => console.log('done');\n```\n\n**Incorrect (Python - domain abbreviations):**\n\n```python\n# Bad: abbreviations require domain knowledge\ndef calc_ttl_amt(ord_itms, disc_pct):\n subtl = sum(itm.prc * itm.qty for itm in ord_itms)\n return subtl * (1 - disc_pct)\n\n# What does this even mean?\ncust_addr_ln1 = get_cust_info()['addr']['ln1']\n```\n\n**Correct (Python - spelled out):**\n\n```python\n# Good: no guessing required\ndef calculate_total_amount(order_items, discount_percentage):\n subtotal = sum(item.price * item.quantity for item in order_items)\n return subtotal * (1 - discount_percentage)\n\ncustomer_address_line1 = get_customer_info()['address']['line1']\n```\n\n**Incorrect (Go - excessive shortening):**\n\n```go\n// Bad: Go convention taken too far\nfunc procReq(r *http.Req, w http.RespWriter) {\n usr := getUsr(r.Ctx())\n if usr == nil {\n w.WriteHdr(401)\n return\n }\n rsp := buildRsp(usr)\n json.NewEnc(w).Enc(rsp)\n}\n```\n\n**Correct (Go - balanced naming):**\n\n```go\n// Good: clear but still idiomatic Go\nfunc processRequest(request *http.Request, writer http.ResponseWriter) {\n user := getUser(request.Context())\n if user == nil {\n writer.WriteHeader(401)\n return\n }\n response := buildResponse(user)\n json.NewEncoder(writer).Encode(response)\n}\n```\n\n### Acceptable Abbreviations\n\nSome abbreviations are so universally understood they are acceptable:\n\n| Abbreviation | Meaning | Context |\n|--------------|---------|---------|\n| `id` | identifier | Universal |\n| `url` | uniform resource locator | Web development |\n| `api` | application programming interface | Programming |\n| `http` | hypertext transfer protocol | Web development |\n| `db` | database | When context is obvious |\n| `io` | input/output | Systems programming |\n| `i`, `j`, `k` | loop indices | Small loop scopes |\n| `e`, `err` | error | Go convention, catch blocks |\n| `ctx` | context | Go convention only |\n\n### When NOT to Apply\n\n- Well-established domain acronyms (HTML, JSON, SQL, UUID)\n- Industry-standard abbreviations (API, HTTP, URL)\n- Language-specific idioms (`err` in Go, `e` in catch blocks)\n- Mathematical notation in algorithms\n\n### Benefits\n\n- Zero decoding time for readers\n- New team members productive immediately\n- No tribal knowledge required\n- Reduces bugs from misinterpreted abbreviations\n- Code is searchable with full words\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4048,"content_sha256":"760cba4afa295da286c340d977cf5e0e929ff59941ab0185e8bcfdc8afa9220a"},{"filename":"references/name-avoid-generic.md","content":"---\ntitle: Avoid Generic Names\nimpact: MEDIUM-HIGH\nimpactDescription: Generic names like data, info, temp force readers to trace through code to understand meaning, adding 10-30 seconds per occurrence\ntags: name, specificity, clarity, readability, context\n---\n\n## Avoid Generic Names\n\nNames like `data`, `info`, `temp`, `item`, `result`, `value`, and `thing` tell you nothing about what they contain. They force readers to trace through the code to understand what they represent. Replace generic names with specific ones that describe the actual content or purpose.\n\n**Incorrect (generic names):**\n\n```typescript\n// Bad: What kind of data? What info? Result of what?\nasync function process(data: any): Promise\u003cany> {\n const info = await fetchInfo(data.id);\n const result = transform(info);\n const temp = validate(result);\n return temp;\n}\n\n// Bad: What items? What values?\nfunction handleItems(items: any[]) {\n for (const item of items) {\n const value = item.getValue();\n doSomething(value);\n }\n}\n```\n\n**Correct (specific names):**\n\n```typescript\n// Good: Names describe actual content\nasync function processOrder(orderRequest: OrderRequest): Promise\u003cOrderConfirmation> {\n const inventoryStatus = await fetchInventoryStatus(orderRequest.productId);\n const pricedOrder = applyPricing(inventoryStatus);\n const validatedOrder = validateOrder(pricedOrder);\n return validatedOrder;\n}\n\n// Good: Names reveal what's being processed\nfunction applyDiscounts(lineItems: LineItem[]) {\n for (const lineItem of lineItems) {\n const originalPrice = lineItem.getPrice();\n applyDiscount(originalPrice);\n }\n}\n```\n\n**Incorrect (Python - vague naming):**\n\n```python\n# Bad: What object? What info? Temp for what?\ndef process(obj):\n data = obj.get_data()\n info = parse(data)\n temp = []\n for thing in info:\n if thing.is_valid():\n temp.append(thing)\n result = format(temp)\n return result\n```\n\n**Correct (Python - descriptive naming):**\n\n```python\n# Good: Every name tells a story\ndef filter_active_subscriptions(customer):\n subscription_records = customer.get_subscriptions()\n parsed_subscriptions = parse_subscription_data(subscription_records)\n active_subscriptions = []\n for subscription in parsed_subscriptions:\n if subscription.is_active():\n active_subscriptions.append(subscription)\n formatted_report = format_subscription_report(active_subscriptions)\n return formatted_report\n```\n\n**Incorrect (Go - placeholder names):**\n\n```go\n// Bad: What response? What value? Temp for?\nfunc handle(w http.ResponseWriter, r *http.Request) {\n data := getData(r)\n if data == nil {\n return\n }\n result := process(data)\n temp := format(result)\n value := validate(temp)\n respond(w, value)\n}\n```\n\n**Correct (Go - meaningful names):**\n\n```go\n// Good: Clear data flow\nfunc handleUserProfileRequest(w http.ResponseWriter, r *http.Request) {\n userCredentials := extractCredentials(r)\n if userCredentials == nil {\n return\n }\n profileData := loadUserProfile(userCredentials)\n formattedProfile := formatProfileResponse(profileData)\n validatedResponse := validateResponse(formattedProfile)\n sendJSONResponse(w, validatedResponse)\n}\n```\n\n### Worst Offenders\n\n| Generic Name | What to Ask | Better Alternative |\n|--------------|-------------|-------------------|\n| `data` | Data about what? | `userData`, `sensorReadings`, `configPayload` |\n| `info` | Information about what? | `userInfo`, `connectionInfo`, `errorDetails` |\n| `temp` | Temporary what? | `pendingChanges`, `intermediateSum`, `bufferContent` |\n| `item` | Item from what collection? | `cartItem`, `menuOption`, `searchResult` |\n| `result` | Result of what operation? | `queryResult`, `validationResult`, `calculatedTotal` |\n| `value` | Value of what? | `inputValue`, `configValue`, `computedScore` |\n| `list` | List of what? | `userList`, `errorMessages`, `availableOptions` |\n| `obj` / `object` | Object representing what? | `userProfile`, `paymentRecord`, `configSettings` |\n| `str` / `string` | String containing what? | `userName`, `errorMessage`, `formattedDate` |\n| `num` / `number` | Number representing what? | `retryCount`, `totalPrice`, `userAge` |\n\n### When NOT to Apply\n\n- Truly generic utilities (e.g., `stringify(value)` in a serialization library)\n- Short-lived variables in tiny scopes (3-5 lines max)\n- Generic type parameters (`T`, `K`, `V` are conventional)\n- Language-specific idioms (e.g., `_` for unused variables)\n\n### Benefits\n\n- Code reads like documentation\n- No need to trace variable origins\n- Bugs become obvious when wrong data flows through\n- Refactoring is safer with distinct names\n- Code reviews catch misuse immediately\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4723,"content_sha256":"98517342a68dc397e3009eafbba3d1796ae9eef095f76749539bb4f846ef1174"},{"filename":"references/name-consistent-vocabulary.md","content":"---\ntitle: Use Consistent Vocabulary Throughout\nimpact: MEDIUM-HIGH\nimpactDescription: Inconsistent terminology causes 15-20% longer comprehension time and leads to bugs when developers confuse similar-sounding concepts\ntags: name, consistency, vocabulary, ubiquitous-language, domain\n---\n\n## Use Consistent Vocabulary Throughout\n\nWhen the same concept is called different things in different places, readers must mentally map synonyms and wonder if they refer to the same thing or subtly different concepts. Pick one term for each concept and use it everywhere - in code, comments, documentation, and conversation.\n\n**Incorrect (inconsistent terminology):**\n\n```typescript\n// Bad: Same concept, different names\nclass UserService {\n fetchUser(id: string): User { ... } // \"fetch\"\n getCustomer(id: string): User { ... } // \"get\" + \"customer\"\n retrieveAccount(id: string): User { ... } // \"retrieve\" + \"account\"\n loadClient(id: string): User { ... } // \"load\" + \"client\"\n}\n\n// Confusing: Are these the same or different?\nconst user = service.fetchUser(id);\nconst customer = service.getCustomer(id);\nconst account = service.retrieveAccount(id);\n```\n\n**Correct (consistent vocabulary):**\n\n```typescript\n// Good: One term per concept\nclass UserService {\n getUser(id: string): User { ... }\n getUserByEmail(email: string): User { ... }\n getUsersByRole(role: string): User[] { ... }\n getCurrentUser(): User { ... }\n}\n\n// Clear: All operations work with \"users\" and \"get\"\nconst user = service.getUser(id);\nconst admin = service.getUserByEmail(adminEmail);\nconst editors = service.getUsersByRole('editor');\n```\n\n**Incorrect (Python - mixed terminology):**\n\n```python\n# Bad: delete vs remove vs destroy vs clear\nclass CartManager:\n def delete_item(self, item_id): ...\n def remove_product(self, product_id): ...\n def destroy_entry(self, entry_id): ...\n def clear_line(self, line_id): ...\n\n# Bad: create vs add vs insert vs new\ndef create_order(data): ...\ndef add_order(data): ...\ndef insert_order(data): ...\ndef new_order(data): ...\n```\n\n**Correct (Python - unified vocabulary):**\n\n```python\n# Good: consistent verbs throughout\nclass CartManager:\n def remove_item(self, item_id): ...\n def remove_all_items(self): ...\n\n# Good: one verb for creation\ndef create_order(order_data): ...\ndef create_line_item(item_data): ...\ndef create_payment(payment_data): ...\n```\n\n**Incorrect (Go - entity name confusion):**\n\n```go\n// Bad: Is it a Job, Task, Work, or Process?\ntype JobQueue struct {\n tasks []Task\n workPool chan Work\n procs map[string]*Process\n}\n\nfunc (q *JobQueue) AddTask(t Task) error { ... }\nfunc (q *JobQueue) SubmitWork(w Work) error { ... }\nfunc (q *JobQueue) EnqueueJob(j Job) error { ... }\n```\n\n**Correct (Go - unified terminology):**\n\n```go\n// Good: Everything is a Job\ntype JobQueue struct {\n pendingJobs []Job\n workerPool chan Job\n runningJobs map[string]*Job\n}\n\nfunc (q *JobQueue) SubmitJob(job Job) error { ... }\nfunc (q *JobQueue) CancelJob(jobID string) error { ... }\nfunc (q *JobQueue) GetJobStatus(jobID string) JobStatus { ... }\n```\n\n### Create a Project Vocabulary\n\nDocument your chosen terms:\n\n| Concept | Use This | NOT These |\n|---------|----------|-----------|\n| Retrieve data | `get` | fetch, retrieve, load, find, obtain |\n| Create entity | `create` | add, insert, new, make, build |\n| Remove entity | `delete` | remove, destroy, clear, erase |\n| Modify entity | `update` | modify, change, edit, patch |\n| Person using app | `user` | customer, client, account, member |\n\n### When NOT to Apply\n\n- When integrating with external APIs that use different terminology\n- When domain experts use specific terms (use their ubiquitous language)\n- When language idioms dictate different verbs (e.g., `append` in Go)\n\n### Benefits\n\n- Concepts are immediately recognizable\n- No mental mapping between synonyms required\n- Search and replace works reliably\n- Onboarding is faster with predictable naming\n- Domain model stays clear and unambiguous\n\n### References\n\n- Domain-Driven Design: \"Ubiquitous Language\" pattern\n- Clean Code: \"Use Solution Domain Names\" and \"Use Problem Domain Names\"\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":4158,"content_sha256":"c92156104e6eb498547f23f40893ad77a77861031efce9fce6ee3606f10c095a"},{"filename":"references/name-intention-revealing.md","content":"---\ntitle: Use Intention-Revealing Names\nimpact: MEDIUM-HIGH\nimpactDescription: Descriptive names reduce code review time by 30-40% and eliminate the need for explanatory comments\ntags: name, readability, self-documenting, clarity\n---\n\n## Use Intention-Revealing Names\n\nNames should answer why something exists, what it does, and how it is used. If a name requires a comment to explain its purpose, the name itself should be improved. Good names make code self-documenting, reducing cognitive load and preventing misuse.\n\n**Incorrect (names require comments to understand):**\n\n```typescript\n// Bad: What does 'd' represent?\nconst d = 86400000; // milliseconds in a day\n\nfunction calc(a: number[], f: number): number {\n // Bad: What is being calculated? What are a and f?\n return a.filter(x => x > f).length;\n}\n\n// Bad: What does this list contain?\nconst list = getUsers();\n```\n\n**Correct (names reveal intent):**\n\n```typescript\nconst MILLISECONDS_PER_DAY = 86400000;\n\nfunction countItemsAboveThreshold(items: number[], threshold: number): number {\n return items.filter(item => item > threshold).length;\n}\n\nconst activeUsers = getActiveUsers();\n```\n\n**Incorrect (Python - cryptic names):**\n\n```python\n# Bad: What is being processed?\ndef proc(d, t):\n r = []\n for i in d:\n if i['ts'] > t:\n r.append(i)\n return r\n```\n\n**Correct (Python - intention-revealing):**\n\n```python\ndef filter_events_after_timestamp(events, cutoff_timestamp):\n recent_events = []\n for event in events:\n if event['timestamp'] > cutoff_timestamp:\n recent_events.append(event)\n return recent_events\n```\n\n**Incorrect (Go - opaque abbreviations):**\n\n```go\n// Bad: What does this function do?\nfunc proc(c *Ctx, req *Req) (*Resp, error) {\n u := c.GetU()\n if u == nil {\n return nil, ErrNA\n }\n return &Resp{D: u.D}, nil\n}\n```\n\n**Correct (Go - clear purpose):**\n\n```go\nfunc fetchUserProfile(ctx *RequestContext, request *ProfileRequest) (*ProfileResponse, error) {\n currentUser := ctx.GetAuthenticatedUser()\n if currentUser == nil {\n return nil, ErrNotAuthenticated\n }\n return &ProfileResponse{DisplayName: currentUser.DisplayName}, nil\n}\n```\n\n### When NOT to Apply\n\n- Loop indices (`i`, `j`, `k`) in simple iterations where scope is tiny\n- Mathematical formulas where single-letter variables are conventional (e.g., `x`, `y` for coordinates)\n- Lambda parameters in very short, obvious transformations\n\n### Benefits\n\n- Code becomes self-documenting\n- Eliminates need for explanatory comments\n- Reduces onboarding time for new developers\n- Makes code review faster and more effective\n- Prevents bugs caused by misunderstanding variable purpose\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":2698,"content_sha256":"ec26b726dae0a4fb14d378b399d2fe03156409ae98874724eb32f73053a87367"},{"filename":"references/name-nouns-for-data.md","content":"---\ntitle: Use Nouns for Data, Verbs for Actions\nimpact: MEDIUM-HIGH\nimpactDescription: Consistent noun/verb naming reduces misuse errors by making it immediately clear whether something stores data or performs an action\ntags: name, conventions, semantics, functions, variables\n---\n\n## Use Nouns for Data, Verbs for Actions\n\nVariables, constants, and properties represent data - name them with nouns or noun phrases. Functions and methods perform actions - name them with verbs or verb phrases. This grammatical consistency creates intuitive expectations about what code does, making it easier to read and harder to misuse.\n\n**Incorrect (confused naming conventions):**\n\n```typescript\n// Bad: verb name for data\nconst getUser = { id: 1, name: 'Alice' };\n\n// Bad: noun name for function\nfunction user(id: number): User {\n return database.find(id);\n}\n\n// Bad: adjective for boolean action\nfunction valid(input: string): boolean {\n return input.length > 0;\n}\n\n// Confusing usage\nconst result = user(getUser.id); // Which is the function?\n```\n\n**Correct (nouns for data, verbs for actions):**\n\n```typescript\n// Good: noun for data\nconst currentUser = { id: 1, name: 'Alice' };\n\n// Good: verb for function\nfunction fetchUser(id: number): User {\n return database.find(id);\n}\n\n// Good: verb for boolean-returning function\nfunction isValid(input: string): boolean {\n return input.length > 0;\n}\n\n// Clear usage\nconst result = fetchUser(currentUser.id);\n```\n\n**Incorrect (Python - mixed conventions):**\n\n```python\n# Bad: function named like data\ndef order_total(order):\n return sum(item.price for item in order.items)\n\n# Bad: data named like action\ncalculate_tax = 0.08\nprocess_items = ['apple', 'banana']\n\n# Confusing: is this calling a function or accessing data?\ntotal = order_total # Missing parentheses - but name suggests data\n```\n\n**Correct (Python - clear conventions):**\n\n```python\n# Good: verb phrase for function\ndef calculate_order_total(order):\n return sum(item.price for item in order.items)\n\n# Good: nouns for data\ntax_rate = 0.08\navailable_items = ['apple', 'banana']\n\n# Clear: obviously a function call\ntotal = calculate_order_total(cart)\n```\n\n**Incorrect (Go - unclear entity types):**\n\n```go\n// Bad: function looks like a type\nfunc User(id int) *UserModel {\n return db.Find(id)\n}\n\n// Bad: variable looks like function\nvar fetchData = Response{Status: 200}\n```\n\n**Correct (Go - proper conventions):**\n\n```go\n// Good: function uses verb\nfunc GetUser(id int) *UserModel {\n return db.Find(id)\n}\n\n// Good: variable uses noun\nvar apiResponse = Response{Status: 200}\n```\n\n### Common Patterns\n\n| Entity Type | Convention | Examples |\n|-------------|------------|----------|\n| Variables | Noun/noun phrase | `user`, `orderItems`, `totalPrice` |\n| Constants | Noun (often UPPER_CASE) | `MAX_RETRIES`, `DefaultTimeout` |\n| Functions | Verb/verb phrase | `fetchUser`, `calculateTotal`, `validateInput` |\n| Boolean functions | `is`, `has`, `can`, `should` | `isValid`, `hasPermission`, `canEdit` |\n| Properties | Noun | `user.name`, `order.total` |\n\n### When NOT to Apply\n\n- Factory functions may use nouns when the pattern is conventional (e.g., `NewUser()` in Go)\n- Builder pattern methods may chain noun-like names\n- DSL or fluent APIs may prioritize readability over grammar\n\n### Benefits\n\n- Instantly distinguishes data from behavior\n- Reduces cognitive load when reading code\n- Prevents accidental misuse (calling data, accessing functions)\n- Makes code structure predictable\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3495,"content_sha256":"284b49d2d6e0ad8efea5f9dd645170982cd0639dc91ea262639414cf9aa3f3f6"},{"filename":"references/name-string-interpolation.md","content":"---\ntitle: Prefer String Interpolation Over Concatenation\nimpact: MEDIUM-HIGH\nimpactDescription: Replaces 2-5 concatenation operators per string with a single template, reducing off-by-one quote errors by 80% and making string structure visible at a glance\ntags: name, string-interpolation, readability, template-literals, f-strings\n---\n\n## Prefer String Interpolation Over Concatenation\n\nString concatenation scatters the output format across operators and quotes, making it hard to see the final shape of the string. Template literals (JavaScript/TypeScript), f-strings (Python), and format strings (Go, Rust) keep the structure intact with values inserted inline, so readers can see exactly what the output looks like.\n\n**Incorrect (string concatenation):**\n\n```typescript\nfunction formatUserGreeting(user: User): string {\n return 'Hello, ' + user.firstName + ' ' + user.lastName +\n '! You have ' + user.unreadCount + ' unread messages.';\n}\n\nfunction buildApiUrl(baseUrl: string, version: number, resource: string): string {\n return baseUrl + '/api/v' + version + '/' + resource;\n}\n\nfunction logOrderEvent(orderId: string, status: string, timestamp: Date): void {\n console.log('[' + timestamp.toISOString() + '] Order ' + orderId +\n ' changed to ' + status);\n}\n```\n\n**Correct (template literals):**\n\n```typescript\nfunction formatUserGreeting(user: User): string {\n return `Hello, ${user.firstName} ${user.lastName}! You have ${user.unreadCount} unread messages.`;\n}\n\nfunction buildApiUrl(baseUrl: string, version: number, resource: string): string {\n return `${baseUrl}/api/v${version}/${resource}`;\n}\n\nfunction logOrderEvent(orderId: string, status: string, timestamp: Date): void {\n console.log(`[${timestamp.toISOString()}] Order ${orderId} changed to ${status}`);\n}\n```\n\n**Incorrect (Python - string concatenation and % formatting):**\n\n```python\ndef format_error_message(code, endpoint, method):\n # Concatenation: hard to see the shape\n return \"Error \" + str(code) + \" on \" + method + \" \" + endpoint\n\ndef build_query(table, columns, condition):\n # % formatting: positional args drift from placeholders\n return \"SELECT %s FROM %s WHERE %s\" % (\", \".join(columns), table, condition)\n```\n\n**Correct (Python - f-strings):**\n\n```python\ndef format_error_message(code, endpoint, method):\n return f\"Error {code} on {method} {endpoint}\"\n\ndef build_query(table, columns, condition):\n return f\"SELECT {', '.join(columns)} FROM {table} WHERE {condition}\"\n```\n\n**Incorrect (Go - fmt.Sprintf with positional verbs):**\n\n```go\nfunc formatLogEntry(level string, component string, message string) string {\n return level + \" [\" + component + \"] \" + message\n}\n```\n\n**Correct (Go - fmt.Sprintf):**\n\n```go\nfunc formatLogEntry(level string, component string, message string) string {\n return fmt.Sprintf(\"%s [%s] %s\", level, component, message)\n}\n```\n\n### When NOT to Apply\n\n- Building SQL queries (use parameterized queries, never interpolation)\n- When string pieces come from a loop or dynamic collection (use `join`)\n- Performance-critical paths with many concatenations (use `strings.Builder` in Go, `StringBuilder` in Java)\n- Simple two-part concatenation where readability is equivalent\n\n### Benefits\n\n- String structure visible at a glance without tracing through operators\n- Eliminates off-by-one quote/space errors between concatenated segments\n- Easier to add or reorder interpolated values\n- Fewer characters and less visual noise than concatenation\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3480,"content_sha256":"6132c499df95251177e8421ca65c09267279ce4d232441e1d5778bf14abbfb79"},{"filename":"references/scope-minimal-diff.md","content":"---\ntitle: Keep Changes Small and Reviewable\nimpact: HIGH\nimpactDescription: PRs over 400 lines have 50% lower defect detection and 2x more post-merge bugs (SmartBear study of 2,500 reviews at Cisco)\ntags: scope, diff-size, review-quality, pr-hygiene\n---\n\n## Keep Changes Small and Reviewable\n\nEvery simplification should produce the smallest possible diff. Large diffs exhaust reviewers, hide bugs in noise, and make rollbacks painful. A 50-line PR gets thorough review; a 500-line PR gets rubber-stamped. Small changes also make git bisect effective when bugs emerge.\n\n**Incorrect (kitchen-sink simplification):**\n\n```diff\n# PR: \"Simplify user service\" - 847 lines changed\n\n- import { UserRepository } from './repositories/user';\n- import { Logger } from '../shared/logger';\n- import { Cache } from '../shared/cache';\n+ import { UserRepository } from '@/repos';\n+ import { log } from '@/utils';\n+ import { cache } from '@/utils';\n\n- export class UserService {\n- private repo: UserRepository;\n- private logger: Logger;\n- private cache: Cache;\n-\n- constructor(repo: UserRepository, logger: Logger, cache: Cache) {\n- this.repo = repo;\n- this.logger = logger;\n- this.cache = cache;\n- }\n+ export class UserService {\n+ constructor(\n+ private repo = new UserRepository(),\n+ private log = log,\n+ private cache = cache\n+ ) {}\n\n- async getUser(id: string): Promise\u003cUser | null> {\n- const cached = await this.cache.get(`user:${id}`);\n- if (cached !== null) {\n- return cached;\n- }\n- const user = await this.repo.findById(id);\n- if (user !== null) {\n- await this.cache.set(`user:${id}`, user);\n- }\n- return user;\n- }\n+ getUser = async (id: string) =>\n+ this.cache.get(`user:${id}`) ??\n+ this.repo.findById(id).then(u => (u && this.cache.set(`user:${id}`, u), u));\n\n# ... 800 more lines of \"improvements\" across 15 files\n```\n\n**Correct (atomic, focused simplification):**\n\n```diff\n# PR 1: \"Simplify UserService.getUser caching logic\" - 12 lines changed\n\n async getUser(id: string): Promise\u003cUser | null> {\n- const cached = await this.cache.get(`user:${id}`);\n- if (cached !== null) {\n- return cached;\n- }\n- const user = await this.repo.findById(id);\n- if (user !== null) {\n- await this.cache.set(`user:${id}`, user);\n- }\n- return user;\n+ const cacheKey = `user:${id}`;\n+ const cached = await this.cache.get(cacheKey);\n+ if (cached) return cached;\n+\n+ const user = await this.repo.findById(id);\n+ if (user) await this.cache.set(cacheKey, user);\n+ return user;\n }\n\n# PR 2 (separate): \"Update import paths to use aliases\" - if needed\n# PR 3 (separate): \"Simplify UserService constructor\" - if needed\n```\n\n### Guidelines for Diff Size\n\n- Aim for under 200 lines changed per PR\n- Never exceed 400 lines without explicit approval\n- If simplification grows large, split into multiple PRs\n- Each PR should have a single, clear purpose\n\n### Benefits\n\n- Reviewers can give full attention to each change\n- Bugs are easier to spot in small diffs\n- Rollbacks affect minimal code\n- CI/CD cycles are faster\n- Merge conflicts are less likely\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3141,"content_sha256":"3f135a72b77e26a4d1042b68a32d91f597cf2782d7e13e96cdfd2ef28c2179a5"},{"filename":"references/scope-no-global-rewrites.md","content":"---\ntitle: Avoid Global Rewrites and Architectural Changes\nimpact: HIGH\nimpactDescription: Global renames touching 50+ files cause 3-5 days of merge conflicts and require 2-10x more regression testing than scoped changes\ntags: scope, global-changes, architecture, risk-management\n---\n\n## Avoid Global Rewrites and Architectural Changes\n\nCode simplification is not the time for sweeping changes. Global renames, mass migrations, or architectural shifts disguised as \"simplification\" create merge conflict nightmares and require extensive testing. These changes need dedicated planning, not drive-by implementation.\n\n**Incorrect (global rename during simplification):**\n\n```typescript\n// Task: Simplify the checkout module\n// \"To simplify, I'll rename 'cart' to 'basket' everywhere for clarity\"\n\n// 127 files changed:\n// - src/components/Cart.tsx -> Basket.tsx\n// - src/hooks/useCart.ts -> useBasket.ts\n// - src/stores/cartStore.ts -> basketStore.ts\n// - src/api/cart/*.ts -> basket/*.ts\n// - src/types/cart.ts -> basket.ts\n// - tests/**/*cart* -> *basket*\n// - docs/cart.md -> basket.md\n// Plus all import statements, variable names, comments...\n\n// \"Also modernized the state management while I was at it\"\n// Migrated from Redux to Zustand across 45 files\n```\n\n**Correct (contained simplification):**\n\n```typescript\n// Task: Simplify the checkout module\n// PR only touches checkout logic, preserves existing naming\n\n// Before - checkout/processOrder.ts\nexport async function processOrder(cart: Cart, payment: Payment) {\n const validation = validateCart(cart);\n if (validation.isValid === false) {\n throw new ValidationError(validation.errors);\n }\n const total = calculateTotal(cart);\n const tax = calculateTax(total, cart.shippingAddress);\n const finalAmount = total + tax;\n const charge = await chargePayment(payment, finalAmount);\n if (charge.success === true) {\n return createOrder(cart, charge);\n }\n throw new PaymentError(charge.error);\n}\n\n// After - same file, same naming conventions\nexport async function processOrder(cart: Cart, payment: Payment) {\n validateCart(cart); // throws on invalid\n\n const total = calculateTotal(cart);\n const finalAmount = total + calculateTax(total, cart.shippingAddress);\n\n const charge = await chargePayment(payment, finalAmount);\n if (!charge.success) throw new PaymentError(charge.error);\n\n return createOrder(cart, charge);\n}\n\n// Note: \"cart vs basket\" naming discussion logged as TECH-1234\n// Note: State management modernization planned for Q3 roadmap\n```\n\n### Changes That Require Separate Planning\n\n| Change Type | Why It's Not Simplification |\n|-------------|---------------------------|\n| Global renames | Touches every file, massive merge conflicts |\n| Dependency upgrades | Requires compatibility testing |\n| Architecture changes | Needs design review and migration plan |\n| Pattern migrations | (callbacks->promises, classes->hooks) Need incremental rollout |\n| Directory restructuring | Breaks imports across entire codebase |\n\n### When NOT to Apply\n\n- During a planned, scheduled migration sprint\n- When the global change is the explicit, approved task\n- When a breaking change is already coordinated with the team\n\n### Benefits\n\n- Other developers can continue merging their work\n- No surprise regressions in unrelated features\n- Changes can be reviewed by domain experts\n- Rollback is possible without reverting weeks of work\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3403,"content_sha256":"610243f69d2ef027f1603138eadbc6a4da19cfaf59bf0b2a13a0280fec2ef4cc"},{"filename":"references/scope-no-unrelated-refactors.md","content":"---\ntitle: No Unrelated Refactors\nimpact: HIGH\nimpactDescription: Mixed-purpose PRs have 60% higher revert rates and block unrelated deployments when issues arise\ntags: scope, focus, single-responsibility, pr-hygiene\n---\n\n## No Unrelated Refactors\n\nEvery PR should have exactly one purpose. When simplifying code, resist the urge to fix \"while you're in there\" issues. Unrelated changes pollute git history, complicate reviews, and create deployment dependencies. If you spot other issues, create separate tickets.\n\n**Incorrect (opportunistic refactoring):**\n\n```typescript\n// Task: Simplify the calculateDiscount function\n// PR description: \"Simplify discount calc + some cleanup\"\n\n// Change 1: The actual task (correct)\nfunction calculateDiscount(price: number, tier: string): number {\n const rates = { bronze: 0.05, silver: 0.10, gold: 0.15 };\n return price * (rates[tier] ?? 0);\n}\n\n// Change 2: \"Noticed this could use optional chaining\" (wrong!)\nfunction getOrderTotal(order: Order): number {\n return order?.items?.reduce((sum, i) => sum + i.price, 0) ?? 0;\n}\n\n// Change 3: \"Fixed inconsistent naming\" (wrong!)\n// Renamed userPreferences -> userPrefs across 8 files\n\n// Change 4: \"Removed dead code I found\" (wrong!)\n// Deleted 3 unused utility functions\n\n// Change 5: \"Updated to arrow functions for consistency\" (wrong!)\n// Converted 12 function declarations to arrows\n```\n\n**Correct (single-purpose PR):**\n\n```typescript\n// Task: Simplify the calculateDiscount function\n// PR description: \"Simplify discount calculation using lookup table\"\n\n// Before\nfunction calculateDiscount(price: number, tier: string): number {\n let discount = 0;\n if (tier === 'bronze') {\n discount = price * 0.05;\n } else if (tier === 'silver') {\n discount = price * 0.10;\n } else if (tier === 'gold') {\n discount = price * 0.15;\n }\n return discount;\n}\n\n// After - ONLY this function changes\nfunction calculateDiscount(price: number, tier: string): number {\n const rates = { bronze: 0.05, silver: 0.10, gold: 0.15 };\n return price * (rates[tier] ?? 0);\n}\n\n// Other observations logged as separate tickets:\n// - TECH-1234: Add optional chaining to getOrderTotal\n// - TECH-1235: Standardize preferences naming convention\n// - TECH-1236: Remove unused utility functions\n```\n\n### The \"While You're In There\" Anti-Pattern\n\nCommon temptations to resist:\n- \"I'll just update these imports too\"\n- \"This variable name is misleading, quick fix\"\n- \"Found some dead code, might as well delete it\"\n- \"The formatting here is inconsistent\"\n- \"This could use modern syntax\"\n\nEach of these deserves its own PR or ticket.\n\n### When NOT to Apply\n\n- When the \"unrelated\" change is required for the main change to work\n- When fixing a typo in a comment you're already modifying\n- When the project explicitly allows bundled cleanup (rare)\n\n### Benefits\n\n- PRs are easy to review, approve, or reject independently\n- Reverts are surgical, not catastrophic\n- git blame shows clear intent for each change\n- Deployment risk is isolated\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3011,"content_sha256":"4bb711c9930f9cbbbbb81f1d11f42b3334f1b413a7502236af066a40c619bc56"},{"filename":"references/scope-recent-code-only.md","content":"---\ntitle: Focus on Recently Modified Code Only\nimpact: HIGH\nimpactDescription: Touching old stable code increases risk by 3-5x and adds 40%+ review time for code reviewers unfamiliar with legacy context\ntags: scope, focus, recent-changes, risk-reduction, git-history\n---\n\n## Focus on Recently Modified Code Only\n\nCode simplification should target recently modified code unless explicitly asked otherwise. Old, stable code has survived production testing and carries hidden assumptions. Simplifying it introduces risk without proportional benefit, and reviewers lack fresh context to validate changes.\n\n**Incorrect (simplifying unrelated legacy code):**\n\n```typescript\n// Task: Simplify the new getUserProfile function\n// PR includes changes to:\n\n// 1. The new function (correct target)\nasync function getUserProfile(id: string): Promise\u003cProfile> {\n const user = await db.users.findById(id);\n return user ? mapToProfile(user) : null;\n}\n\n// 2. Legacy auth module last touched 2 years ago (wrong!)\n// \"While I was here, I noticed this could be cleaner...\"\nfunction validateSession(token: string): boolean {\n // Simplified from 50 lines to 20\n return jwt.verify(token, SECRET) && !isExpired(token);\n}\n\n// 3. Old utility last touched 18 months ago (wrong!)\n// \"This helper was verbose, made it more functional...\"\nconst formatDate = (d: Date) => d.toISOString().split('T')[0];\n```\n\n**Correct (focused on recent code only):**\n\n```typescript\n// Task: Simplify the new getUserProfile function\n// PR only touches getUserProfile (added last week)\n\n// Before\nasync function getUserProfile(id: string): Promise\u003cProfile> {\n const result = await db.users.findById(id);\n if (result !== null && result !== undefined) {\n const profile = mapToProfile(result);\n return profile;\n } else {\n return null;\n }\n}\n\n// After - only this function changes\nasync function getUserProfile(id: string): Promise\u003cProfile> {\n const user = await db.users.findById(id);\n return user ? mapToProfile(user) : null;\n}\n\n// Legacy validateSession: untouched (stable for 2 years)\n// Old formatDate utility: untouched (stable for 18 months)\n```\n\n### When NOT to Apply\n\n- When explicitly asked to audit or simplify legacy code\n- When fixing a bug that requires touching old code\n- When old code blocks the current feature and must be modified anyway\n- When performing a planned, scoped refactoring sprint\n\n### How to Identify Recent Code\n\nUse git history to find active areas:\n\n```bash\n# Find files with most recent changes\ngit log --since=\"30 days ago\" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20\n\n# Check who owns which sections\ngit blame path/to/file.ts\n\n# Find high-churn files (complexity signals)\ngit log --since=\"90 days ago\" --name-only --pretty=format: | sort | uniq -c | sort -rn\n```\n\nPrioritize files mentioned in open PRs, recent issues, or with many recent commits.\n\n### Benefits\n\n- PRs stay focused and reviewable\n- Reviewers have full context on changed code\n- Risk is contained to code already under active development\n- git blame remains meaningful for historical debugging\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3088,"content_sha256":"c2a527069b48eb700fe087347fe6c06bc946659ca5ec6069bf383853e0c98cc0"},{"filename":"references/scope-respect-boundaries.md","content":"---\ntitle: Respect Module and Component Boundaries\nimpact: HIGH\nimpactDescription: Cross-boundary changes require multiple team approvals, increase coupling by 30%, and double the testing surface area\ntags: scope, boundaries, modules, coupling, encapsulation\n---\n\n## Respect Module and Component Boundaries\n\nWhen simplifying code, stay within the current module or component boundary. Reaching across boundaries to \"simplify\" creates tight coupling, violates encapsulation, and pulls in reviewers from other teams. Each module has its own owners, contracts, and release cycles.\n\n**Incorrect (crossing boundaries to simplify):**\n\n```typescript\n// Task: Simplify the OrderService in the orders module\n// \"I can simplify this by directly accessing the user database\"\n\n// orders/OrderService.ts\nimport { db } from '../users/database'; // Crossing into users module!\nimport { UserCache } from '../users/cache'; // Crossing into users module!\nimport { formatAddress } from '../shipping/utils'; // Crossing into shipping!\n\nclass OrderService {\n async createOrder(userId: string, items: Item[]) {\n // \"Simplified\" by bypassing UserService\n const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);\n const cached = UserCache.get(userId); // Direct cache access\n\n // \"Simplified\" by inlining shipping logic\n const address = formatAddress(user.address); // Using internal util\n\n return this.repo.create({ user, items, address });\n }\n}\n\n// Now OrderService depends on:\n// - users module internals (database, cache)\n// - shipping module internals (utils)\n// Breaking changes in any module will break orders\n```\n\n**Correct (respecting boundaries):**\n\n```typescript\n// Task: Simplify the OrderService in the orders module\n// Stays within orders module, uses public APIs\n\n// orders/OrderService.ts\nimport { UserService } from '../users'; // Public API only\nimport { ShippingService } from '../shipping'; // Public API only\n\nclass OrderService {\n constructor(\n private users: UserService,\n private shipping: ShippingService,\n private repo: OrderRepository\n ) {}\n\n async createOrder(userId: string, items: Item[]) {\n const user = await this.users.getByIdOrThrow(userId);\n const address = await this.shipping.getFormattedAddress(userId);\n\n return this.repo.create({ userId, items, shippingAddress: address });\n }\n}\n\n// If UserService or ShippingService APIs are clunky, request changes\n// through proper channels - don't bypass them\n```\n\n### Boundary Violations to Avoid\n\n| Violation | Why It's Harmful |\n|-----------|-----------------|\n| Direct database access across modules | Bypasses business logic, breaks encapsulation |\n| Importing internal utilities | Creates hidden dependencies |\n| Accessing private/internal APIs | Will break on internal refactors |\n| Copying code from other modules | Creates drift and duplication |\n| Modifying other modules \"to simplify\" | Requires other team's review/approval |\n\n### When NOT to Apply\n\n- When you own both modules and they're tightly related\n- When the boundary itself is the problem (propose boundary changes separately)\n- When working in a monolith with no clear module ownership\n- When the public API is genuinely missing needed functionality (request it)\n\n### Benefits\n\n- Each module can evolve independently\n- Changes only require review from affected team\n- Testing is scoped to the current module\n- Coupling stays low and explicit\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3443,"content_sha256":"631ef27e5959461f74d55650e2aa3fc1d821b8b2189d87981793599ca2c9f1a1"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Community Code Simplification Best Practices","type":"text"}]},{"type":"paragraph","content":[{"text":"Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Principles","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Context First","type":"text","marks":[{"type":"strong"}]},{"text":": Understand project conventions before making any changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Behavior Preservation","type":"text","marks":[{"type":"strong"}]},{"text":": Change how code is written, never what it does","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scope Discipline","type":"text","marks":[{"type":"strong"}]},{"text":": Focus on recently modified code, keep diffs small","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Clarity Over Brevity","type":"text","marks":[{"type":"strong"}]},{"text":": Explicit, readable code beats clever one-liners","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Apply","type":"text"}]},{"type":"paragraph","content":[{"text":"Reference these guidelines when:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Simplifying or cleaning up recently modified code","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reducing nesting, complexity, or duplication","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Improving naming and readability","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Applying language-specific idiomatic patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reviewing code for maintainability issues","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Rule Categories by Priority","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Priority","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Category","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Impact","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Prefix","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Rules","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"1","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Context Discovery","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CRITICAL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"ctx-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"4","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"2","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Behavior Preservation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CRITICAL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"behave-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"6","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"3","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Scope Management","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIGH","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"scope-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"5","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"4","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Control Flow Simplification","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIGH","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"flow-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"9","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"5","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Naming and Clarity","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MEDIUM-HIGH","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"name-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"6","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"6","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Duplication Reduction","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MEDIUM","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"dup-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"5","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"7","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Dead Code Elimination","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MEDIUM","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"dead-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"5","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"8","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Language Idioms","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"LOW-MEDIUM","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"idiom-","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"7","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quick Reference","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Context Discovery (CRITICAL)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ctx-read-claude-md","type":"text","marks":[{"type":"link","attrs":{"href":"references/ctx-read-claude-md.md","title":null}},{"type":"code_inline"}]},{"text":" - Always read CLAUDE.md before simplifying","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ctx-detect-lint-config","type":"text","marks":[{"type":"link","attrs":{"href":"references/ctx-detect-lint-config.md","title":null}},{"type":"code_inline"}]},{"text":" - Check for linting and formatting configs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ctx-follow-existing-patterns","type":"text","marks":[{"type":"link","attrs":{"href":"references/ctx-follow-existing-patterns.md","title":null}},{"type":"code_inline"}]},{"text":" - Match existing code style in file and project","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ctx-project-over-generic","type":"text","marks":[{"type":"link","attrs":{"href":"references/ctx-project-over-generic.md","title":null}},{"type":"code_inline"}]},{"text":" - Project conventions override generic best practices","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Behavior Preservation (CRITICAL)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-preserve-outputs","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-preserve-outputs.md","title":null}},{"type":"code_inline"}]},{"text":" - Preserve all return values and outputs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-preserve-errors","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-preserve-errors.md","title":null}},{"type":"code_inline"}]},{"text":" - Preserve error messages, types, and handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-preserve-api","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-preserve-api.md","title":null}},{"type":"code_inline"}]},{"text":" - Preserve public function signatures and types","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-preserve-side-effects","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-preserve-side-effects.md","title":null}},{"type":"code_inline"}]},{"text":" - Preserve side effects (logging, I/O, state changes)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-no-semantics-change","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-no-semantics-change.md","title":null}},{"type":"code_inline"}]},{"text":" - Forbid subtle semantic changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"behave-verify-before-commit","type":"text","marks":[{"type":"link","attrs":{"href":"references/behave-verify-before-commit.md","title":null}},{"type":"code_inline"}]},{"text":" - Verify behavior preservation before finalizing","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Scope Management (HIGH)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scope-recent-code-only","type":"text","marks":[{"type":"link","attrs":{"href":"references/scope-recent-code-only.md","title":null}},{"type":"code_inline"}]},{"text":" - Focus on recently modified code only","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scope-minimal-diff","type":"text","marks":[{"type":"link","attrs":{"href":"references/scope-minimal-diff.md","title":null}},{"type":"code_inline"}]},{"text":" - Keep changes small and reviewable","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scope-no-unrelated-refactors","type":"text","marks":[{"type":"link","attrs":{"href":"references/scope-no-unrelated-refactors.md","title":null}},{"type":"code_inline"}]},{"text":" - No unrelated refactors","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scope-no-global-rewrites","type":"text","marks":[{"type":"link","attrs":{"href":"references/scope-no-global-rewrites.md","title":null}},{"type":"code_inline"}]},{"text":" - Avoid global rewrites and architectural changes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"scope-respect-boundaries","type":"text","marks":[{"type":"link","attrs":{"href":"references/scope-respect-boundaries.md","title":null}},{"type":"code_inline"}]},{"text":" - Respect module and component boundaries","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Control Flow Simplification (HIGH)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-early-return","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-early-return.md","title":null}},{"type":"code_inline"}]},{"text":" - Use early returns to reduce nesting","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-guard-clauses","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-guard-clauses.md","title":null}},{"type":"code_inline"}]},{"text":" - Use guard clauses for preconditions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-no-nested-ternaries","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-no-nested-ternaries.md","title":null}},{"type":"code_inline"}]},{"text":" - Never use nested ternary operators","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-explicit-over-dense","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-explicit-over-dense.md","title":null}},{"type":"code_inline"}]},{"text":" - Prefer explicit control flow over dense expressions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-flatten-nesting","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-flatten-nesting.md","title":null}},{"type":"code_inline"}]},{"text":" - Flatten deep nesting to maximum 2-3 levels","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-single-responsibility","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-single-responsibility.md","title":null}},{"type":"code_inline"}]},{"text":" - Each code block should do one thing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-positive-conditions","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-positive-conditions.md","title":null}},{"type":"code_inline"}]},{"text":" - Prefer positive conditions over double negatives","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-optional-chaining","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-optional-chaining.md","title":null}},{"type":"code_inline"}]},{"text":" - Use optional chaining and nullish coalescing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"flow-boolean-simplification","type":"text","marks":[{"type":"link","attrs":{"href":"references/flow-boolean-simplification.md","title":null}},{"type":"code_inline"}]},{"text":" - Simplify boolean expressions","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Naming and Clarity (MEDIUM-HIGH)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-intention-revealing","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-intention-revealing.md","title":null}},{"type":"code_inline"}]},{"text":" - Use intention-revealing names","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-nouns-for-data","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-nouns-for-data.md","title":null}},{"type":"code_inline"}]},{"text":" - Use nouns for data, verbs for actions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-avoid-abbreviations","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-avoid-abbreviations.md","title":null}},{"type":"code_inline"}]},{"text":" - Avoid cryptic abbreviations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-consistent-vocabulary","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-consistent-vocabulary.md","title":null}},{"type":"code_inline"}]},{"text":" - Use consistent vocabulary throughout","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-avoid-generic","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-avoid-generic.md","title":null}},{"type":"code_inline"}]},{"text":" - Avoid generic names","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"name-string-interpolation","type":"text","marks":[{"type":"link","attrs":{"href":"references/name-string-interpolation.md","title":null}},{"type":"code_inline"}]},{"text":" - Prefer string interpolation over concatenation","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"6. Duplication Reduction (MEDIUM)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dup-rule-of-three","type":"text","marks":[{"type":"link","attrs":{"href":"references/dup-rule-of-three.md","title":null}},{"type":"code_inline"}]},{"text":" - Apply the rule of three","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dup-no-single-use-helpers","type":"text","marks":[{"type":"link","attrs":{"href":"references/dup-no-single-use-helpers.md","title":null}},{"type":"code_inline"}]},{"text":" - Avoid single-use helper functions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dup-extract-for-clarity","type":"text","marks":[{"type":"link","attrs":{"href":"references/dup-extract-for-clarity.md","title":null}},{"type":"code_inline"}]},{"text":" - Extract only when it improves clarity","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dup-avoid-over-abstraction","type":"text","marks":[{"type":"link","attrs":{"href":"references/dup-avoid-over-abstraction.md","title":null}},{"type":"code_inline"}]},{"text":" - Prefer duplication over premature abstraction","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dup-data-driven","type":"text","marks":[{"type":"link","attrs":{"href":"references/dup-data-driven.md","title":null}},{"type":"code_inline"}]},{"text":" - Use data-driven patterns over repetitive conditionals","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"7. Dead Code Elimination (MEDIUM)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dead-remove-unused","type":"text","marks":[{"type":"link","attrs":{"href":"references/dead-remove-unused.md","title":null}},{"type":"code_inline"}]},{"text":" - Delete unused code artifacts","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dead-delete-not-comment","type":"text","marks":[{"type":"link","attrs":{"href":"references/dead-delete-not-comment.md","title":null}},{"type":"code_inline"}]},{"text":" - Delete code, never comment it out","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dead-remove-obvious-comments","type":"text","marks":[{"type":"link","attrs":{"href":"references/dead-remove-obvious-comments.md","title":null}},{"type":"code_inline"}]},{"text":" - Remove comments that state the obvious","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dead-keep-why-comments","type":"text","marks":[{"type":"link","attrs":{"href":"references/dead-keep-why-comments.md","title":null}},{"type":"code_inline"}]},{"text":" - Keep comments that explain why, not what","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"dead-remove-todo-fixme","type":"text","marks":[{"type":"link","attrs":{"href":"references/dead-remove-todo-fixme.md","title":null}},{"type":"code_inline"}]},{"text":" - Remove stale TODO/FIXME comments","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"8. Language Idioms (LOW-MEDIUM)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-ts-strict-types","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-ts-strict-types.md","title":null}},{"type":"code_inline"}]},{"text":" - Use strict types over any (TypeScript)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-ts-const-assertions","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-ts-const-assertions.md","title":null}},{"type":"code_inline"}]},{"text":" - Use const assertions and readonly (TypeScript)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-rust-question-mark","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-rust-question-mark.md","title":null}},{"type":"code_inline"}]},{"text":" - Use ? for error propagation (Rust)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-rust-iterator-chains","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-rust-iterator-chains.md","title":null}},{"type":"code_inline"}]},{"text":" - Use iterator chains when clearer (Rust)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-python-comprehensions","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-python-comprehensions.md","title":null}},{"type":"code_inline"}]},{"text":" - Use comprehensions for simple transforms (Python)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-go-error-handling","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-go-error-handling.md","title":null}},{"type":"code_inline"}]},{"text":" - Handle errors immediately (Go)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idiom-prefer-language-builtins","type":"text","marks":[{"type":"link","attrs":{"href":"references/idiom-prefer-language-builtins.md","title":null}},{"type":"code_inline"}]},{"text":" - Prefer language and stdlib builtins","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Workflow","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Discover context","type":"text","marks":[{"type":"strong"}]},{"text":": Read CLAUDE.md, lint configs, examine existing patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Identify scope","type":"text","marks":[{"type":"strong"}]},{"text":": Focus on recently modified code unless asked to expand","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Apply transformations","type":"text","marks":[{"type":"strong"}]},{"text":": Use rules in priority order (CRITICAL first)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verify behavior","type":"text","marks":[{"type":"strong"}]},{"text":": Ensure outputs, errors, and side effects remain identical","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Keep diffs minimal","type":"text","marks":[{"type":"strong"}]},{"text":": Small, focused changes that are easy to review","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"How to Use","type":"text"}]},{"type":"paragraph","content":[{"text":"Read individual reference files for detailed explanations and code examples:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Section definitions","type":"text","marks":[{"type":"link","attrs":{"href":"references/_sections.md","title":null}}]},{"text":" - Category structure and impact levels","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Rule template","type":"text","marks":[{"type":"link","attrs":{"href":"assets/templates/_template.md","title":null}}]},{"text":" - Template for adding new rules","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reference Files","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"File","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"references/_sections.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/_sections.md","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Category definitions and ordering","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"assets/templates/_template.md","type":"text","marks":[{"type":"link","attrs":{"href":"assets/templates/_template.md","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Template for new rules","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"metadata.json","type":"text","marks":[{"type":"link","attrs":{"href":"metadata.json","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Version and reference information","type":"text"}]}]}]}]}]},"metadata":{"date":"2026-11-02","name":"code-simplifier","author":"@skillopedia","source":{"stars":220,"repo_name":"dot-skills","origin_url":"https://github.com/pproenca/dot-skills/blob/HEAD/skills/.curated/code-simplifier/SKILL.md","repo_owner":"pproenca","body_sha256":"1850c855a6368316c42883968becdc7238bd3cb62722c6ca9d521251d613eaa7","cluster_key":"b1c681a7fcc01a731b00616f54e58e0411925f3ca23e8c746d82189cc411ae4a","clean_bundle":{"format":"clean-skill-bundle-v1","source":"pproenca/dot-skills/skills/.curated/code-simplifier/SKILL.md","text_bytes":283656,"source_commit":"cf93c57cac89d6fc3e4194686000411567f5caf3","skills_sh_rank":9663,"attachment_count":52,"text_attachments":52,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"skills/.curated/code-simplifier/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"software-engineering","category_label":"Engineering"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"software-engineering","import_tag":"skills-sh-top20k-2026-11","description":"Code simplification skill for improving clarity, consistency, and maintainability while preserving exact behavior. Use when simplifying code, reducing complexity, cleaning up recent changes, applying refactoring patterns, or improving readability. Triggers on tasks involving code cleanup, simplification, refactoring, or readability improvements."}},"renderedAt":1793755387434}

Community Code Simplification Best Practices Comprehensive code simplification guide for AI agents and LLMs. Contains 47 rules across 8 categories, prioritized by impact from critical (context discovery, behavior preservation) to incremental (language idioms). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics. Core Principles 1. Context First : Understand project conventions before making any changes 2. Behavior Preservation : Change how code is written, never what it does 3. Scope Discipline : Focus on r…