{"data":{"slug":"discovered-e27986862f002c2f003a393fa2db912ba74715a089ef8c45","title":"Code Simplification","summary":"Simplify working code to improve readability and maintainability without changing its behavior, including code pasted into a chat or flagged during a review.","url":"https:\/\/skillshunter.net\/skills\/discovered-e27986862f002c2f003a393fa2db912ba74715a089ef8c45","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-e27986862f002c2f003a393fa2db912ba74715a089ef8c45","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-e27986862f002c2f003a393fa2db912ba74715a089ef8c45.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-e27986862f002c2f003a393fa2db912ba74715a089ef8c45\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Name the target (files, symbols, or pasted code) and specify what you can check behavior with: tests, a runnable project, or neither. Read the project's guidance (`AGENTS.md`, `CLAUDE.md`, or a contributing guide) and the code next to the target.","instructions":"---\nname: andino-code-simplification\ndescription: Use when working code is harder to read or change than it needs to be (deep nesting, long functions, unclear names, duplication, dead code, single-use abstractions); when asked to simplify or clean up code without changing behavior, including code pasted into a chat; or when a review flags readability. Not for fixing bugs, adding features or making code faster. Operates under Andino Workflow governance.\n---\n\n# Simplify code without changing what it does\n\nInternal method ID: `andino-code-simplification` (alias: `code-simplification`).\n\n> **Andino Workflow Member Skill**\n> Operates under Andino Workflow: proportional investigation, evidence-based\n> decisions, one durable checkpoint and clean handoff. Do not invoke the workflow\n> recursively. Loading this resource changes neither tools nor permissions.\n\n## Purpose\n\nMake working code faster to read, change and debug while every caller sees the same behavior.\nRemove accidental complexity and keep the domain rules and the names that carry them. The\nmeasure is the 2 AM on-call test, not line count: how quickly a reader woken by an alert can\nlocate a decision, trace its effects and explain its failure path. Every retained change\ncarries evidence that behavior did not move.\n\n## Trigger and non-trigger\n\nUse when a feature works but its code is heavier than it needs to be; when a review flags\nnesting, long functions, unclear names, duplication or dead code; when code written under\ntime pressure, or logic scattered by successive merges, has to become readable; or when\nsomeone asks to simplify or clean up code, including code pasted into a chat.\n\nDo not select, or stop and report, when:\n\n- the request changes behavior (a bug fix, a feature, a contract change): keep it separate.\n- the goal is speed. Hot paths are unidiomatic on purpose (unrolled loops, bitwise tricks,\n  in-place mutation, pre-allocated buffers); performance work owns them.\n- the code is a legal, regulatory, tax or cryptographic calculation written step by step so\n  an auditor can compare it with its specification. Keep the steps.\n- the code is about to be rewritten or deleted.\n- the code is already clear, or you cannot yet say what it does or why a guard, an ordering\n  or an abstraction exists. Read more first; skip what stays unclear.\n- the candidate is outside the requested target, which defaults to the current diff.\n- the candidate is a whole file or folder nothing uses (output, caches, old notes):\n  `repo-clean`.\n\n## Select a resource, not a second lifecycle\n\nLoad only the resource the current need names. It runs inside this procedure and current\nauthority; it starts no second plan.\n\n| Current need | Resource | Skip when |\n| :--- | :--- | :--- |\n| Before\/after recipes for TypeScript, Python and React, and the behavior traps that make a \"simpler\" form differ | [patterns and behavior traps](resources\/patterns-and-anti-patterns.md) | The change needs no recipe |\n| A touched file contains `simplify-ignore` markers | [protected regions](resources\/protected-regions.md) | No touched file has markers |\n| Seeing one pass end to end, with a runnable old-versus-new harness | [worked example](resources\/worked-example.md) | The procedure is already clear |\n\n## Prerequisites\n\nName the target (files, symbols or pasted code) and what you can check behavior with: tests,\na runnable project, or neither. Read the project's guidance (`AGENTS.md`, `CLAUDE.md`, a\ncontributing guide) and the code next to the target. A caller you cannot see stays UNKNOWN\nand is treated as relying on today's behavior.\n\n## Procedure\n\n1. **Choose the safety net.** Pick the row that matches what you have; it decides what must\n   exist before the first edit.\n\n   | What you have | Before the first edit |\n   | --- | --- |\n   | A repository whose passing tests pin the behavior you will touch | Run them. They must pass before and after, with no test edited. |\n   | A repository whose tests fail | Stop and report the failing tests. Simplification needs a green baseline. |\n   | A repository whose tests are missing, or miss behavior the change could affect | Add characterization tests in a new test file that pin today's behavior (the list in step 2), run them green against the old code, and keep them. |\n   | Code with no runnable project (pasted into a chat, an excerpt) | Simplify it. When a runtime is available, run the old and new versions side by side on named edge cases; otherwise reason through each named case. Never make tests a condition for helping. |\n\n   Done when the row is chosen and its safety net exists and passes on the old code.\n\n2. **Learn what must stay observable (Chesterton's Fence).** Before changing or removing\n   anything, find out why it exists. Answer from evidence:\n   - What is the code's responsibility? What calls it, and what does it call?\n   - Which inputs does it accept, including defaults, `None`\/`null`, empty, zero, negative\n     and odd truthy values such as `1` or `\"yes\"`? What does it return, in what shape?\n   - Which exceptions does it raise, with which types and messages? Callers may match on them.\n   - Which reads and side effects does it have (writes, logs, audit entries, events,\n     awaits), in what order and how many times, including on paths that fail partway?\n   - Why might it be written this way? Read `git log`, `git blame`, incident notes and\n     comments for guards, orderings and workarounds that look removable.\n   - Which tests pin which of these, and which does no test pin?\n   - Does a touched file contain `simplify-ignore` markers? If so, read\n     [protected regions](resources\/protected-regions.md) and hash each block now.\n\n   Done when every question has an answer or is recorded as UNKNOWN, and every UNKNOWN on\n   code you will change has a characterization test or a named check.\n\n3. **Find concrete opportunities.** Scan the target for these signals. Each fix is the\n   smallest change that removes the signal.\n\n   | Signal | Example | Simplification |\n   | --- | --- | --- |\n   | Deep nesting (3+ levels) | `if`\/`else` pyramid | Guard clauses with early exits, in the same order and with the same exits |\n   | Long function (50+ lines) | several responsibilities | Named helpers that mirror the domain steps |\n   | Nested ternary | `a ? x : b ? y : z` | `if`\/`else` chain, `switch` or lookup table |\n   | Boolean flag parameter | `create(user, true, false)` | Options object or separate functions, only where the signature is not public |\n   | Opaque or repeated condition | the same compound `if` in several places | One predicate named for the domain decision |\n   | Generic or abbreviated name | `data`, `tmp`, `res`, `usr`, `cfg` | A name that says what it holds; universal short forms (`id`, `url`) stay |\n   | Misleading name | a `get` that also writes | A name that matches the behavior |\n   | Comment that restates the code | `\/\/ increment counter` | Delete it |\n   | Duplicated logic | the same rule written twice | One shared function, only when it is the same rule |\n   | Dead code | unused import, unreachable branch, commented-out block | Remove it under [the evidence rule](#remove-what-nothing-uses) |\n   | Wrapper or abstraction with one user | pass-through, factory with one product, strategy with one strategy | Call the target directly under [the evidence rule](#remove-what-nothing-uses) |\n   | Redundant type assertion | a cast to the type already inferred | Remove it |\n\n   A structural change that needs a design decision, such as replacing prop drilling with\n   context, is a judgment call: report it instead of applying it. Done when every candidate\n   is either chosen with its reading problem named, or left alone with a reason.\n\n4. **Pin what the tests miss.** For each chosen candidate, list the behaviors from step 2 it\n   could touch that no test pins. Add a characterization test for each in a new test file,\n   or, for code with no project, name the case you will run or reason through. Done when\n   every such behavior has a test that passes on the old code, or a named case.\n\n5. **Change one thing at a time.** For each candidate: make the change, run the focused\n   checks, keep it when they pass, undo it and reconsider when they fail. Test each change\n   before starting the next, so a failure points at one change. Before keeping a change,\n   answer:\n   - Same result for every supported input, including the odd ones from step 2?\n   - Same exception types and messages?\n   - Same side effects, in the same order and count?\n   - Do the existing tests pass without modification?\n\n   Record a real bug found on the way and fix it after this pass, in a separate change with\n   its own test.\n\n6. **Judge the whole diff.** Run the relevant suite and the project's build, linter and type\n   checker; compare protected-region hashes. Read the diff as a caller and as the on-call\n   engineer: easier to understand, consistent with the codebase, reviewable, something a\n   teammate would approve? Revert any change that made the code harder to read; not every\n   attempt succeeds. Done when every retained change passes and every revert has a reason.\n\n7. **Report** with the Simplification Ledger described in Output.\n\n## Rules for every simplification\n\n### Preserve behavior exactly\n\nChange how the code says it, never what it does. Inputs, outputs, return shape, exception\ntypes and messages, side effects and their order, and edge-case results stay identical. If\nyou cannot show that a change preserves behavior, do not make it. These look equivalent and\nare not:\n\n- strict and truthy checks: `x is True`, `x == True` or `x === true` versus `if x` (they\n  differ for `\"yes\"` or `2`); `!= null` (null and undefined) versus `!== null` or a truthy\n  test; `a ?? b` versus `a || b` when `a` can be `\"\"` or `0`;\n- an `async` wrapper: without `async`, a synchronous throw from the callee escapes as a\n  thrown error instead of a rejected promise, and a plain value comes back where callers got\n  a promise;\n- iteration: `for...of` rejects array-likes that an index loop accepts;\n- defaults: `options or {}` versus `{} if options is None else options`; an `encoding=`\n  argument the original call did not pass;\n- concurrency: sequential `await`s turned into `Promise.all` without proof that the\n  operations are independent.\n\nNever delete or relax error handling because a condition \"should not happen\", and never\nchange an exception's type or message. Recipes and more traps are in\n[patterns and behavior traps](resources\/patterns-and-anti-patterns.md).\n\n### Follow project conventions\n\nSimplification makes code more consistent with its codebase, not with outside preferences.\nMatch the project's import order and module system, function declaration style, naming,\nerror-handling pattern and depth of type annotations. A change that breaks local consistency\nis churn.\n\n### Prefer clarity over cleverness\n\nExplicit code beats compact code whenever the compact form makes a reader pause. A six-line\n`if`\/`else` beats a nested ternary, a dense regular expression or a chained `reduce`. Types\ndocument structure, not intent: `res` typed as `UserRecord` is still opaque next to\n`authenticatedUser`.\n\n### Remove what nothing uses\n\nRemove unused imports, unreachable branches, commented-out code, and an abstraction with one\nimplementation and one caller, once a search of the whole repository finds no other user:\nimports and re-exports, string or reflective references (`getattr`, dynamic `import()`,\nregistries, configuration files) and the package's public exports. When the name is public\nAPI of a published package, a plugin or hook point, or the search cannot see every caller,\nkeep it and say so in the report. Leftovers of this kind inside the target are part of the\ncode you were asked to simplify, not a separate clean-up.\n\n### Keep what carries a reason\n\n- A comment that explains why (a flaky API, a platform bug, an incident, a promise to\n  customers) stays; a comment that restates what the code does goes.\n- A guard or an ordering whose reason you found in history, an incident note or a comment\n  stays. Add a short comment when the reason lived only in history.\n- Code inside `simplify-ignore` markers stays byte for byte, indentation included. Hash each\n  block before and after, and call it unchanged only when the hashes match. When flattening\n  the code around a block would shift its indentation, keep the nesting around it and say so.\n  Details: [protected regions](resources\/protected-regions.md).\n\n### Maintain balance\n\nOver-simplification is the failure on the other side:\n\n- Inlining a called helper that names a domain rule (`isSessionExpired(session)`) leaks\n  low-level detail into every call site.\n- Functions that look alike today but serve different business rules change independently:\n  duplication is cheaper than the wrong abstraction. Merging unrelated logic is not simpler.\n- A defensive check stays even when today's callers never trigger it. Remove error handling\n  only when the caller contract makes the case impossible.\n- A wrapper can change behavior at its boundary (an `async` wrapper, a `try` that converts\n  errors, a copy that protects the caller), and some abstractions serve testability or a\n  second implementation that really exists. Check what it contributes before removing it.\n\n### Keep the diff in scope\n\nSimplify the requested target (the current change when none is named) and report candidates\nelsewhere instead of fixing them. Past 500 changed lines, use an automated transform\n(codemod, AST rewrite, scripted edit) instead of hand edits, in reviewable commits.\n\n## Shortcuts that break simplification\n\n| Shortcut | Reality |\n| --- | --- |\n| \"Fewer lines is always simpler.\" | Comprehension speed is the measure. A one-line nested ternary is not simpler than a five-line `if`\/`else`. |\n| \"It works; leave it alone.\" | Code that is hard to read is hard to fix when it breaks. Simplify while the tests are green. |\n| \"I'll clean up this unrelated file too.\" | Unscoped changes bloat the diff and risk regressions in code nobody asked you to touch. Report them instead. |\n| \"I'll refactor while adding this feature.\" | Two changes in one diff are hard to review, revert and bisect. Split them. |\n| \"The caller never passes null, so the check can go.\" | Unexpected input happens. Keep the check unless the contract makes the case impossible. |\n| \"This abstraction might be useful later.\" | A speculative abstraction is complexity without value now. Remove it once the evidence rule shows nothing uses it; re-add it when a second use arrives. |\n| \"The original author must have had a reason.\" | Maybe: check history, incident notes and callers. When none shows a reason and nothing uses the code, it is residue of iteration. |\n| \"It names a domain concept, so I keep the unused class.\" | Domain names protect code that is called. A class nothing calls protects nothing. |\n| \"Unused imports are a separate clean-up.\" | They sit in the code you were asked to simplify. Remove them in the same pass. |\n| \"The protected block is untouched.\" | Only a hash comparison shows that. Compute it before you claim it. |\n| \"There are no tests for pasted code, so I can't help.\" | Simplify it, check it by running or reasoning through named cases, and say what stays unverified. |\n\n## Red flags\n\nStop and re-check when you see:\n\n- an existing test assertion or fixture changed to make it pass;\n- an exception type or message changed, validation relaxed or error handling removed;\n- a byte changed inside a `simplify-ignore` block, an identifier the block reads renamed\n  outside it, or a claim about a block with no hash;\n- a named domain helper inlined, or a comment that explained why deleted;\n- side effects or async operations reordered, or an exported signature changed;\n- \"simplified\" code that is longer or harder to follow, or renamed to your taste rather\n  than the project's conventions;\n- code changed that you could not explain before changing it;\n- many simplifications in one untested change, stylistic churn, or edits outside the target.\n\n## Ownership and permission boundary\n\nAndino coordinates selection, shared progress, resource guards and final status from\nevidence. This skill owns its procedure, resources and checks, and coordinator brevity never\ntruncates them. In the workflow it is the refactor step: after a feature turns green under\n`tdd` and before `code-review`, so reviewers see the design without accidental complexity.\nWith an active Andino ticket, record the ledger there with one `NEXT ACTION`. Loading this\nskill grants no commit, push, publication or deployment authority.\n\n## Output\n\nA Simplification Ledger with one entry per retained change:\n\n```markdown\n### `<file>::<symbol>`\n- Reading problem: <what made it hard to follow>\n- Change: <what you did>\n- Behavior kept: <the inputs, errors and side effects this change could have touched>\n- Check: <command and result, or the old-versus-new comparison and its case count>\n- Metrics: <only numbers a tool produced, naming the tool; omit otherwise>\n```\n\nThen:\n\n- **Left alone:** each candidate you skipped and why (protected, reason found in history,\n  public API, unclear, out of scope, judgment call for the owner).\n- **Checks:** the commands run with their results, the characterization tests added, and\n  each protected block's before and after hash (or \"none\").\n- **Not verified:** what no check covered.\n\nIf nothing changed, say why and which evidence was missing. For code pasted into a chat,\nreply with the simplified code, one line per change, how you checked it (the cases you ran or\nreasoned through), what you left alone and why, and what stays unverified.\n\n## Verification\n\n- [ ] The safety net from step 1 passed on the old code and passes on the new code.\n- [ ] Existing tests pass with no assertion or fixture changed; added characterization tests\n      stay in the repository.\n- [ ] The build, linter and type checker report no new errors or warnings.\n- [ ] Exception types and messages, side-effect order and public signatures are unchanged;\n      no error handling was removed or weakened.\n- [ ] Protected-region hashes were computed before and after, and match.\n- [ ] No unused import, unreachable branch or commented-out code is left in or around the\n      change.\n- [ ] Each change is a reviewable step, the diff holds nothing unrelated, follows the\n      project's conventions, and a teammate or review agent would approve it as a net\n      improvement that the on-call engineer reads faster.\n- [ ] Every retained change has a ledger entry with its check; nothing is claimed without one.\n\n## Worked example\n\n[The worked example](resources\/worked-example.md) flattens a nested telemetry aggregator,\nkeeps a strict `is True` check and a protected digest, and proves both with a runnable\nold-versus-new harness.\n\nAnti-pattern: flatten the function, swap `is True` for a truthy check, re-indent the\nprotected block, then report \"behavior identical, block byte-for-byte unchanged\" from a test\nsuite that never passes `valid: 1`.\n\n## Fallback\n\n- Tests cannot run: follow step 1's last row and list the behavior as not verified.\n- A caller, history or incident record you cannot read stays UNKNOWN: keep the code it would\n  justify removing.\n- Malformed or unmatched `simplify-ignore` markers: stop editing that file and ask.\n- More than 500 lines to change and no automated transform: stop after the first\n  reviewable slice.\n\n## Local resources\n\nThe resources above are packaged with this skill; upstream repositories are not runtime\ndependencies. The MIT notice is in [references\/license.md](references\/license.md).\n\n## Operational example (offline)\n\n```python andino-operational-example\nimport hashlib, json, os\nfrom pathlib import Path\ndef before(x):\n    if x is None: raise TypeError(\"missing\")\n    if x < 0: raise ValueError(\"negative\")\n    return x * 2\ndef after(x):\n    if x is None: raise TypeError(\"missing\")\n    if x < 0: raise ValueError(\"negative\")\n    return 2 * x\ndef observed(fn, x):\n    try: return (\"value\", fn(x))\n    except Exception as e: return (type(e).__name__, str(e))\ndef probe():\n    protected = b\"# simplify-ignore-start\\nFAST = 7\\n# simplify-ignore-end\\n\"\n    p = Path(\"protected.txt\"); p.write_bytes(protected)\n    if os.getenv(\"ANDINO_NEGATIVE\"): p.write_bytes(protected.replace(b\"7\", b\"8\"))\n    equal = all(observed(before, x) == observed(after, x) for x in [None, -2, -1, 0, 1, 2, 100])\n    return {\"behavior_equal\": equal, \"protected_equal\": hashlib.sha256(p.read_bytes()).digest() == hashlib.sha256(protected).digest(), \"cases\": 7}\nprint(json.dumps(probe(), sort_keys=True))\n```\n\nDefault output: `{\"behavior_equal\": true, \"cases\": 7, \"protected_equal\": true}`  \nAdversarial output (`ANDINO_NEGATIVE=1`): `{\"behavior_equal\": true, \"cases\": 7, \"protected_equal\": false}`\n\n## Provenance\n\nAdapted from Addy Osmani's `code-simplification` (addyosmani\/agent-skills,\n`skills\/code-simplification\/SKILL.md`, last changed in commit f1f6fbf, 2026-10-16) under the\nMIT license ([references\/license.md](references\/license.md)): the five principles,\nChesterton's Fence questions, the signal table, the per-change questions, the rationalization\nrows and the verification checklist. The safety-net table, the evidence rule for removal, the\nbehavior traps, protected regions, the Simplification Ledger and the resources are Andino\nadditions. Upstream is audit provenance only; runtime needs no upstream installation or\nnetwork fetch.\n","use_cases":["Refactoring deeply nested or long functions for better readability","Cleaning up code flagged during a code review for clarity","Simplifying code pasted into a chat for easier understanding","Removing accidental complexity from code written under time pressure"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/andinoferdi\/andino-skills\/blob\/639c62b294a835b77a167cc4af1aa1f306d0cc45\/skills\/andino-workflow\/skills\/code-simplification\/SKILL.md","source_commit":"639c62b294a835b77a167cc4af1aa1f306d0cc45","license":null,"version":null,"listing_approved_at":"2026-11-30","created_at":"2026-11-29T10:50:26.000000Z","updated_at":"2026-11-30T06:51:23.000000Z","seo_title":"Code Simplification Tool for Readability and Maintainability","seo_description":"Improve code readability and maintainability without altering behavior. Ideal for refactoring complex, nested, or duplicated code flagged during reviews.","seo_keywords":["code simplification","refactor code","improve code readability","remove accidental complexity","code review cleanup"]}}