Refactor for Code Quality

VerifiedSafe

Remove code duplication, extract shared patterns, and eliminate type casts and `any` types. Run after implementing new features.

Sby Skills Guide Bot
DevelopmentIntermediate
7/23/2026
Claude CodeCursorWindsurfCopilotCodex
#refactoring#code-duplication#type-safety#typescript#code-quality

Recommended for

Automated summary

This skill drives a post-feature refactoring pass: spotting duplicated logic, extracting shared utilities, and eliminating `any` types and type assertions.

Strengths

  • Gives a step-by-step process backed by concrete git and ripgrep commands to list changed files and locate duplicated patterns
  • Explicitly targets type safety: `any`, `as` assertions, non-null assertions, and `void`-based warning suppression
  • Includes a pragmatic carve-out for jscodeshift, allowing one targeted assertion instead of contorting the code around incomplete AST typings
  • Specifies where extracted helpers should live (src/internal/ or next to the only consumer)

Limitations

  • Assumes a Git repo with a main baseline branch and ripgrep installed
  • The grep recipes (`rg ": any"`, `rg " as [A-Z]"`) are TypeScript/JavaScript-specific
  • Offers no guidance on when duplication is acceptable or when a shared helper is premature abstraction
When to use it

Run it right after implementing or bug-fixing a feature, before code review, to clean up duplication and typing debt introduced by the change.

When not to use it

Skip it on non-TypeScript codebases, or when what you need is a functional/correctness review rather than structural cleanup.

Security analysis

Safe
Quality score78/100

The skill is a purely instructional refactoring guide. Its only execution surface is read-only git/ripgrep inspection plus a standard project validation command (`pnpm check`); there are no destructive operations, credential access, outbound data transfer, or obfuscated payloads. The only residual risk is that `pnpm check` runs whatever scripts the host package.json defines, which is a normal and expected behavior for a CI-style check.

Findings
  • •Runs `pnpm check`, which executes project-defined package scripts; assess the target repo's scripts if untrusted.
  • •Uses shell commands (`git diff`, `rg`) but only for read-only inspection; no destructive, network-exfiltration, or obfuscated operations.
How this analysis is made

Examples

Post-feature cleanup
I just finished the new export feature. Review everything changed on this branch against origin/main, remove any duplicated logic, and extract shared helpers where it makes sense.
Type safety sweep
Find every `any` type and type assertion in the files I changed on this branch and replace them with proper interfaces, generics, or type guards.
Shared utility check
Check whether the helper I just added duplicates something that already exists in src/, and either extend the existing one or tell me why a new one is justified.

name: refactor-code-quality description: Remove code duplication, extract shared patterns, and eliminate type casts and any types. Run after implementing new features.

Refactor for Code Quality

After implementing a feature, review the changes to remove code duplication, extract shared patterns, and ensure type safety. This skill enforces the codebase's core principles of modularization and type correctness.

When to Use

  • After implementing any new feature - Review all changed files
  • After fixing bugs - Check if the fix introduced duplication
  • During code review - Identify patterns that should be shared
  • Proactively - Periodically audit the codebase for accumulated duplication

Process

Step 1: Identify All Changed Files on Branch

# See all files changed on this branch compared to main
git diff origin/main --name-only

# See the full diff of all changes on the branch
git diff origin/main

Step 2: Analyze for Code Duplication

Look for these patterns in the changed code:

2a. Repeated Logic Blocks

Search for similar code patterns:

# Look for similar function structures
rg "function.*\(" --type ts -l

# Look for repeated patterns (example: similar conditionals)
rg "if.*===.*null" --type ts -C 2

Signs of duplication:

  • Multiple functions with similar structure but different details
  • Copy-pasted code blocks with minor modifications
  • Switch statements or if-chains that could be data-driven
  • Similar error handling patterns repeated across files

2b. Parallel Logic Instead of Shared Utilities

Check if new code duplicates existing helpers:

# Find existing utility functions in src/
rg "^export (function|const)" src/ --type ts

# Check for similar patterns to what you just added
rg "<pattern-from-your-code>" src/

Questions to ask:

  • Does a helper already exist that does something similar?
  • Can an existing helper be extended to cover the new case?
  • Should this logic be extracted to a shared utility?

Step 3: Analyze for Type Safety Issues

3a. Find any Types

# Search for any types in changed files
rg ": any" --type ts
rg "as any" --type ts
rg "<any>" --type ts

Fix by:

  • Defining proper interfaces or type aliases
  • Using generics for flexible but type-safe code
  • Using unknown with type guards when type is truly unknown

Note: jscodeshift's AST types can make some patterns difficult to type precisely. In cases where jscodeshift's type definitions are incomplete or overly broad, a well-placed type assertion may be acceptable if it improves code clarity. Prefer narrowing with type guards when possible, but don't contort the code just to avoid a single assertion in AST manipulation code.

3b. Find Type Assertions

# Search for type assertions
rg " as [A-Z]" --type ts
rg "(<[A-Z][a-zA-Z]*>)" --type ts

# Search for non-null assertions
rg "!\." --type ts
rg "!\[" --type ts
rg "!;" --type ts

Fix by:

  • Adding proper null checks with early returns
  • Using optional chaining (?.) where appropriate
  • Narrowing types with type guards
  • Fixing the source of the type uncertainty

3c. Find Linter Warning Suppression Hacks

# Search for void used to suppress unused variable warnings
rg "^\s*void \w+;" --type ts

Never use void variable; to suppress unused variable warnings. This is a code smell that hides the real problem. Instead:

  • Remove the parameter if it's not needed
  • Actually use it if it should be doing something

Step 4: Refactor to Remove Duplication

4a. Extract Shared Functions

When you find duplicated logic:

  1. Identify the common pattern - What's the same across all instances?
  2. Identify the variations - What differs? These become parameters.
  3. Create or extend a helper - Place it in the appropriate module:
    • src/internal/ for internal utilities
    • Near the code that uses it if only used in one area

4b. Prefer Shared Context Objects Over Large Argument Bags

When helper functions need many of the same parameters (e.g., j, filePath, warnings, parseExpr, resolveValue), avoid constructing large inline argument objects at each call site. Instead, pass a shared context object plus only the call-specific arguments:

Bad — duplicates the same fields at every call site and bloats the type:

tryResolveBlockLevel({
  j,
  filePath,
  warnings,
  parseExpr,
  resolveValue,
  resolveCall,
  resolveImportInScope,
  resolverImports,
  handlerContext,
  // ...10 more shared fields
  conditional, // ← the only call-specific field
});

Good — pass the shared context and only spell out what's unique:

tryResolveBlockLevel(ctx, { conditional });

Where ctx is a commonly defined context type (e.g., DeclProcessingState, CssHelperConditionalContext) that bundles the shared fields. The helper's type can use Pick<Context, ...> if it only needs a subset.

This pattern:

  • Eliminates repetitive field listings at call sites
  • Makes it obvious which arguments are call-specific vs shared
  • Keeps types in sync automatically (use Pick from the source type)
  • Reduces the chance of forgetting to pass a new field when the context grows

4c. Use Data-Driven Approaches

Replace repetitive conditionals (switch statements, if-chains) with lookup tables or maps.

Step 5: Ensure Proper Type Definitions

  • Replace any types with proper interfaces, type aliases, or generics where feasible
  • Replace type assertions (using "as") with type guards that narrow types safely
  • Replace non-null assertions (the ! operator) with proper null checks and early returns

Note: Some jscodeshift AST patterns are difficult to type precisely. Accept minimal, well-placed assertions when they improve clarity over convoluted type gymnastics.

Step 6: Verify Changes

Run the full validation suite:

pnpm check

This ensures:

  • No type errors introduced
  • No lint violations
  • All tests still pass
  • No dead code created

Step 7: Review Export Organization

Ensure exports are at the top of files (after imports), with non-exported helpers further down.

Step 8: Commit Refactoring Separately

Keep refactoring commits separate from feature commits for cleaner history:

git add <refactored-files>
git commit -m "refactor: extract shared helper for <pattern>

- Reduces duplication in <files>
- Adds proper types for <area>
"
git push

Checklist

Before considering the refactoring complete:

  • [ ] No duplicated logic blocks across files
  • [ ] Similar patterns use shared helpers
  • [ ] Helper functions use shared context objects instead of large argument bags
  • [ ] No unnecessary "any" types (some jscodeshift patterns may require them)
  • [ ] Type assertions minimized and justified (AST manipulation may need some)
  • [ ] No unnecessary non-null assertions (the ! operator)
  • [ ] No void variable; hacks to suppress linter warnings
  • [ ] Exports are at the top of each file
  • [ ] pnpm check passes
  • [ ] Helper functions have descriptive names

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/refactor-for-code-quality-mrx3xzuc' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/refactor-for-code-quality-mrx3xzuc/download' --output '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md.part' && mv '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md.part' '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && test -s '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/refactor-code-quality' && cp -R '.skill-downloads/refactor-for-code-quality-mrx3xzuc' '.claude/skills/refactor-code-quality'

Cursor
test -f '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && test -s '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/refactor-code-quality' && cp -R '.skill-downloads/refactor-for-code-quality-mrx3xzuc' '.cursor/skills/refactor-code-quality'

Codex
test -f '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && test -s '.skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/refactor-code-quality' && cp -R '.skill-downloads/refactor-for-code-quality-mrx3xzuc' '.agents/skills/refactor-code-quality'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/refactor-for-code-quality-mrx3xzuc'

openskills read 'refactor-for-code-quality-mrx3xzuc'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills