Claude Code से legacy code को safely modernize करने की practical guide
Claude Code के साथ legacy code में tests, TypeScript migration, pitfalls, runnable examples और verification workflow.
Legacy modernization बड़े rewrite से शुरू नहीं होनी चाहिए
Legacy code सिर्फ पुराना code नहीं होता। यह वह code है जिसके behavior को साबित करना मुश्किल है, tests कम हैं, original author उपलब्ध नहीं है, और छोटे change से billing, order, support या publishing flow टूट सकता है। Claude Code इस स्थिति में बहुत उपयोगी है, लेकिन इसे bulk rewrite button की तरह इस्तेमाल करना खतरनाक है।
Safe workflow है: पहले read-only investigation, फिर current behavior को tests से lock करना, और उसके बाद छोटे refactor. Characterization test का मतलब है ऐसा test जो अभी system कैसे behave करता है उसे record करे, भले ही वह behavior ideal न हो। Harness को यहां agent की working scaffolding समझें: tests, permissions, commands, project rules और review checklist.
Official Claude Code common workflows में codebase exploration, refactoring, tests, PR और worktrees जैसे flows दिए गए हैं। Legacy modernization में यही mindset चाहिए। Claude Code speed देता है, लेकिन risk boundary और final approval human team के पास रहना चाहिए।
तीन practical use cases
Priority उस file को न दें जो सिर्फ ugly दिखती है। Priority वहां दें जहां uncertainty कम करने से business risk घटता है।
| Use case | Goal | Claude Code क्या कर सकता है | Human review क्या देखे |
|---|---|---|---|
| Order, billing, payment logic | amount और customer status mistakes रोकना | current behavior map करना, tests add करना, edge cases ढूंढना | tax, discount, rounding, compliance |
| JavaScript से TypeScript migration | future changes को safer बनाना | types add करना, any कम करना, type errors batch में fix करना | public API compatibility |
| Callback-heavy या huge functions | maintainability बढ़ाना | responsibility split करना, names suggest करना, diffs explain करना | error handling, retries, side effects |
ClaudeCodeLab में यही flow पुराने publishing scripts, checkout glue code और content transforms पर काम आता है। Main point यह नहीं कि Claude Code जल्दी code लिखे। Main point यह है कि हर diff reviewable size का हो और उसके साथ test या manual verification note हो।
flowchart LR
A[Explore] --> B[Behavior tests]
B --> C[Small refactor]
C --> D[Types and dependencies]
D --> E[Human risk review]
E --> B
पहले read-only audit कराएं
पहला prompt clearly कहे कि files modify नहीं करनी हैं। इस phase में आपको system map चाहिए, patch नहीं।
@src/legacy और @test पढ़ें।
अभी कोई file modify न करें।
यह audit दें:
1. Main files और responsibilities
2. External I/O, database, API, file writes और side effects
3. कौन सा behavior compatible रहना चाहिए
4. Missing tests और high-risk branches
5. Small changes का safest order
Rule clear न हो तो guess न करें, "needs human confirmation" लिखें।
Official How Claude Code works बताता है कि Claude Code files पढ़ सकता है, commands चला सकता है और code edit कर सकता है। यही power useful है, लेकिन पुराने system में first phase को understanding तक सीमित रखना जरूरी है। Natural दिखने वाला improvement भी किसी existing client का contract तोड़ सकता है।
Copy-paste runnable mini example
यह छोटा order processor example है। Real project में database या external payment API हो सकता है, लेकिन workflow same रहेगा।
mkdir legacy-modernization-demo
cd legacy-modernization-demo
npm init -y
npm install -D vitest typescript @types/node
npm pkg set type="module"
npm pkg set scripts.test="vitest run"
npm pkg set scripts.typecheck="tsc --noEmit"
mkdir -p src/legacy test
Old implementation validation, calculation और response shape को एक file में रखता है। यह intentionally terrible code नहीं है। यह वही practical legacy shape है जो production में चलता रहता है और इसलिए डर पैदा करता है।
// src/legacy/orderProcessor.js
export function processOrder(order) {
if (!order || !Array.isArray(order.items) || order.items.length === 0) {
return { status: "error", message: "items is required" };
}
const subtotal = order.items.reduce((sum, item) => {
return sum + item.price * item.qty;
}, 0);
const discount = order.customer?.type === "vip" ? subtotal * 0.1 : 0;
return {
status: "confirmed",
total: subtotal - discount,
items: order.items,
discount
};
}
अब current behavior को Vitest से lock करें। ये tests ideal business model नहीं बनाते, बल्कि accidental breaking change रोकते हैं।
// test/orderProcessor.test.ts
import { describe, expect, it } from "vitest";
import { processOrder } from "../src/legacy/orderProcessor.js";
describe("processOrder legacy behavior", () => {
it("calculates total for a regular customer", () => {
const result = processOrder({
items: [
{ id: "A1", qty: 2, price: 1000 },
{ id: "B2", qty: 1, price: 500 }
],
customer: { id: "C1", type: "regular" }
});
expect(result).toMatchObject({
status: "confirmed",
total: 2500,
discount: 0
});
});
it("applies a 10 percent VIP discount", () => {
const result = processOrder({
items: [{ id: "A1", qty: 1, price: 10000 }],
customer: { id: "C2", type: "vip" }
});
expect(result.status).toBe("confirmed");
expect(result.total).toBe(9000);
expect(result.discount).toBe(1000);
});
it("returns an error when items are empty", () => {
const result = processOrder({
items: [],
customer: { id: "C3", type: "regular" }
});
expect(result.status).toBe("error");
expect(result.message).toContain("items");
});
});
npm test pass होने के बाद ही edit prompt दें।
@src/legacy/orderProcessor.js और @test/orderProcessor.test.ts पढ़ें।
Existing tests green रखते हुए इस code को TypeScript में migrate करें।
Rules:
- public function name processOrder same रखें
- status, total, discount, message behavior preserve करें
- पहले type definitions add करें, फिर responsibilities split करें
- change के बाद npm test और npm run typecheck चलाएं
- बताएं कि हर diff ने कौन सी compatibility preserve की
TypeScript के बाद reviewable structure
Modernized version में types, validation, calculation और orchestration अलग होते हैं। Goal abstraction नहीं है। Goal यह है कि money-related logic review करना आसान हो।
// src/orderTypes.ts
export type CustomerType = "regular" | "vip";
export type OrderItem = {
id: string;
qty: number;
price: number;
};
export type OrderInput = {
items: OrderItem[];
customer: {
id: string;
type: CustomerType;
};
};
export type OrderResult =
| {
status: "confirmed";
total: number;
items: OrderItem[];
discount: number;
}
| {
status: "error";
message: string;
};
// src/validators.ts
import type { OrderInput } from "./orderTypes";
export function validateOrder(order: OrderInput | null | undefined): string | null {
if (!order || !Array.isArray(order.items) || order.items.length === 0) {
return "items is required";
}
return null;
}
// src/calculators.ts
import type { CustomerType, OrderItem } from "./orderTypes";
export function calculateSubtotal(items: OrderItem[]): number {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
export function calculateDiscount(subtotal: number, customerType: CustomerType): number {
return customerType === "vip" ? subtotal * 0.1 : 0;
}
// src/orderProcessor.ts
import { calculateDiscount, calculateSubtotal } from "./calculators";
import type { OrderInput, OrderResult } from "./orderTypes";
import { validateOrder } from "./validators";
export function processOrder(order: OrderInput): OrderResult {
const validationMessage = validateOrder(order);
if (validationMessage) {
return { status: "error", message: validationMessage };
}
const subtotal = calculateSubtotal(order.items);
const discount = calculateDiscount(subtotal, order.customer.type);
return {
status: "confirmed",
total: subtotal - discount,
items: order.items,
discount
};
}
Test import को ../src/orderProcessor पर बदलें और npm test, npm run typecheck फिर चलाएं। इतना छोटा diff reviewer समझ सकता है। अगर same PR में folder move, dependency upgrade, formatting और domain rename सब डाल दिए, तो review कमजोर हो जाएगा।
Dependency updates अलग रखें
Refactor और major dependency upgrade को मिलाना common mistake है। Test fail होने पर पता नहीं चलेगा कि cause TypeScript migration है, API breaking change है, bundler है या आपकी logic change।
पहले Claude Code से inventory बनवाएं।
package.json और lockfile पढ़ें।
अभी कुछ update न करें।
Table दें:
- package
- current version
- recommended target version
- major upgrade है या नहीं
- official migration guide URL
- likely affected files
- update से पहले कौन से tests चाहिए
Destructive या broad operations के लिए permissions conservative रखें। Official Claude Code permissions पढ़ना useful है, खासकर migrations, deletes और deploy commands से पहले। Agent speed तब तक helpful नहीं जब तक approval gate बचा रहे।
Common pitfalls
पहला pitfall है tests से पहले refactor करना। Code clean हो सकता है, लेकिन rounding, discount या error message बदल गया तो regression है।
दूसरा pitfall है Claude Code suggestion को business rule मान लेना। Idiomatic return shape existing clients के लिए compatible हो, यह जरूरी नहीं।
तीसरा pitfall है giant PR. Type migration, logic split, dependency update, file move और formatting को अलग रखना बेहतर है।
चौथा pitfall है error handling को जल्दी “improve” करना। Old systems में null, specific string या unusual HTTP status भी contract हो सकता है।
पांचवा pitfall है documentation छोड़ देना। Claude Code से PR description में compatibility notes, manual verification steps और rollback plan लिखवाएं।
Review और next step
इस workflow को refactoring automation guide, TDD with Claude Code, और documentation generation के साथ use करें। Team rollout में forbidden areas, test commands, domain terms और review rules को CLAUDE.md best practices में लिखना चाहिए।
ClaudeCodeLab teams को Claude Code training, CLAUDE.md templates और legacy modernization consulting देता है। Goal AI rewrite नहीं है। Goal repeatable workflow है जहां tests, permissions और human review साथ काम करते हैं।
मैंने क्या verify किया
मैंने legacy-modernization-demo बनाकर flow test किया: पहले legacy JavaScript order processor, फिर Vitest से तीन behaviors lock किए, फिर TypeScript structure में migrate किया और npm test तथा npm run typecheck चलाए। सबसे बड़ा benefit read-only audit prompt और edit prompt को अलग रखने से मिला। Diff छोटा रहा, और total calculation, VIP discount, empty order error compatibility verify करना आसान हुआ।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.