Refactoriser pour la qualité du code

VérifiéSûr

Supprimer les duplications de code, extraire les motifs communs et éliminer les casts de type et les types `any`. À exécuter après avoir implémenté de nouvelles fonctionnalités.

Spar Skills Guide Bot
DeveloppementIntermédiaire
23/07/2026
Claude CodeCursorWindsurfCopilotCodex
#refactoring#code-duplication#type-safety#typescript#code-quality

Recommandé pour

Synthèse automatique

Ce skill guide une revue de refactoring après l'implémentation d'une fonctionnalité : détecter la duplication de code, extraire des utilitaires partagés et supprimer les types `any` et les assertions de type.

Points forts

  • Fournit une démarche étape par étape appuyée sur des commandes git et ripgrep concrètes pour repérer les fichiers modifiés et les motifs dupliqués
  • Couvre explicitement la sécurité des types : `any`, assertions `as`, assertions non-null et suppressions de warnings via `void`
  • Inclut une consigne nuancée sur jscodeshift qui autorise une assertion ciblée plutôt que de contourner l'API
  • Rappelle quand placer un helper extrait (src/internal/ ou à proximité du code consommateur)

Limites

  • Suppose un dépôt Git avec une branche main de référence et l'outil ripgrep installé
  • Les exemples de recherche (`rg ": any"`, `rg " as [A-Z]"`) sont propres à TypeScript/JavaScript
  • Ne fournit pas de critères pour décider quand la duplication est acceptable ou quand un helper partagé devient prématuré
Quand l'utiliser

À lancer juste après avoir implémenté ou corrigé une fonctionnalité, avant la revue de code, pour nettoyer la duplication et la dette de typage introduites.

Quand l'éviter

À éviter sur un dépôt non-TypeScript ou lorsque vous cherchez une revue fonctionnelle/correctness plutôt qu'un nettoyage structurel.

Analyse de sécurité

Sûr
Score qualité78/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.

Points d'attention
  • •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.
Comment cette analyse est faite

Exemples

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

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

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. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

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 doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/refactor-for-code-quality-mrx3xzuc'

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

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/refactor-for-code-quality-mrx3xzuc/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires