distributions/codex/skills/code-refactoring-patterns/SKILL.md
Systematic approach to refactoring code for improved maintainability, performance, and clarity while preserving functionality
npx skillsauth add organvm-iv-taxis/a-i--skills code-refactoring-patternsInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
A comprehensive guide to refactoring code systematically while maintaining functionality and improving quality.
Smell: Functions over 20-30 lines
Refactor: Extract Method
// Before
function processOrder(order: Order) {
// Validate order (10 lines)
// Calculate totals (15 lines)
// Apply discounts (12 lines)
// Send confirmation (8 lines)
}
// After
function processOrder(order: Order) {
validateOrder(order);
const totals = calculateTotals(order);
const finalPrice = applyDiscounts(totals, order);
sendConfirmation(order, finalPrice);
}
Smell: Same code in multiple places
Refactor: Extract Function/Class
// Before
function formatUserName(user: User) {
return `${user.firstName} ${user.lastName}`;
}
function formatAuthorName(author: Author) {
return `${author.firstName} ${author.lastName}`;
}
// After
function formatFullName(person: { firstName: string; lastName: string }) {
return `${person.firstName} ${person.lastName}`;
}
Smell: Functions with 4+ parameters
Refactor: Parameter Object
// Before
function createUser(
firstName: string,
lastName: string,
email: string,
phone: string,
address: string
) { }
// After
interface UserDetails {
firstName: string;
lastName: string;
email: string;
phone: string;
address: string;
}
function createUser(details: UserDetails) { }
Smell: Classes with many responsibilities
Refactor: Extract Class
// Before
class UserManager {
createUser() { }
deleteUser() { }
sendEmail() { }
generateReport() { }
logActivity() { }
}
// After
class UserService {
createUser() { }
deleteUser() { }
}
class EmailService {
sendEmail() { }
}
class ReportService {
generateReport() { }
}
Smell: Method uses data from another class more than its own
Refactor: Move Method
// Before
class Order {
calculate() {
return this.customer.getDiscount() * this.amount;
}
}
// After
class Customer {
calculateOrderAmount(order: Order) {
return this.getDiscount() * order.amount;
}
}
Break large functions into smaller, named pieces:
// Before
function renderUser(user: User) {
console.log(`<div>`);
console.log(` <h1>${user.firstName} ${user.lastName}</h1>`);
console.log(` <p>${user.email}</p>`);
console.log(`</div>`);
}
// After
function renderUser(user: User) {
console.log(`<div>`);
console.log(` ${renderUserHeader(user)}`);
console.log(` ${renderUserEmail(user)}`);
console.log(`</div>`);
}
function renderUserHeader(user: User) {
return `<h1>${user.firstName} ${user.lastName}</h1>`;
}
function renderUserEmail(user: User) {
return `<p>${user.email}</p>`;
}
Use descriptive names:
// Before
function calc(a: number, b: number) {
return a * b * 0.08;
}
// After
function calculateSalesTax(amount: number, quantity: number) {
const TAX_RATE = 0.08;
return amount * quantity * TAX_RATE;
}
Make complex expressions clear:
// Before
if (platform.toUpperCase().includes('MAC') &&
browser.toUpperCase().includes('IE') &&
wasInitialized() && resized) {
// do something
}
// After
const isMacOS = platform.toUpperCase().includes('MAC');
const isIE = browser.toUpperCase().includes('IE');
const wasResized = wasInitialized() && resized;
if (isMacOS && isIE && wasResized) {
// do something
}
Use inheritance/interfaces instead of switch/if-else chains:
// Before
function getSpeed(vehicle: Vehicle) {
switch (vehicle.type) {
case 'car': return vehicle.speed * 1.0;
case 'bike': return vehicle.speed * 0.8;
case 'truck': return vehicle.speed * 0.6;
}
}
// After
interface Vehicle {
getSpeed(): number;
}
class Car implements Vehicle {
getSpeed() { return this.speed * 1.0; }
}
class Bike implements Vehicle {
getSpeed() { return this.speed * 0.8; }
}
Use early returns and guard clauses:
// Before
function processPayment(payment: Payment) {
if (payment.isValid()) {
if (payment.amount > 0) {
if (payment.method === 'card') {
// process card payment
} else {
// invalid method
}
} else {
// invalid amount
}
} else {
// invalid payment
}
}
// After
function processPayment(payment: Payment) {
if (!payment.isValid()) {
throw new Error('Invalid payment');
}
if (payment.amount <= 0) {
throw new Error('Invalid amount');
}
if (payment.method !== 'card') {
throw new Error('Invalid method');
}
// process card payment
}
# Read the code thoroughly
cat src/feature.ts
# Check tests
cat src/feature.test.ts
# Find all usages
grep -r "functionName" src/
# Run existing tests
npm test src/feature.test.ts
# Add missing tests if needed
# Make one refactoring change
# Run tests
npm test
# Commit if tests pass
git add . && git commit -m "refactor: extract method calculateTotal"
# Repeat for next refactoring
# Run full test suite
npm test
# Check type errors
npx tsc --noEmit
# Verify lint
npm run lint
# Compare before/after if performance-critical
npm run benchmark
Before refactoring:
During refactoring:
After refactoring:
Complements:
❌ Don't:
✅ Do:
development
Dry-run audit + targeted cleanup for shell command history. Currently wraps atuin (stats today, prune, dedup with dated preview artifacts); extensible to zsh/bash/mcfly backends. Always previews before applying — apply commands are echoed for the human to run, never auto-executed. Triggers on "/shell-history-hygiene", "audit atuin", "audit shell history", "clean shell history", "atuin prune", "atuin dedup", "shell history hygiene", "history cleanup". Replaces ad-hoc one-liners (e.g. `... | tee cmd > file.txt` which wrote two files, swallowed dedup output, and left a junk `cmd` file).
tools
Guided Cowork setup — install role-matched plugins, connect your tools, try a skill.
development
Manage AI agent session lifecycles with structured phases (FRAME, SHAPE, BUILD, PROVE), context preservation across sessions, handoff protocols, and session metadata tracking. Triggers on session management, agent lifecycle, or multi-session workflow requests.
tools
Parse a session transcript into a structured Session Governance Index — an annotated bibliography of every file modified and commit made, internal-energy accounting (tool uses, estimated tokens), shipped-vs-tasked atom tally, and classification of missing items as Gaps or Vacuums. Triggers on "visibility-schema-substrate-sweep", "session cascade audit", "session governance audit", or any request to summarize what a session actually produced versus what it was asked to produce.