AI ile Refactoring: Legacy Kodu Modernleştirme
ChatGPT, Cursor, Copilot ile refactoring: legacy code, design pattern, technical debt çözme.
Refactoring = kod aynı işi yapar, daha temiz. AI ile bu 2x hızlı + güvenli. Legacy stack’ten modern’e geçiş artık imkansız değil.
Test-First Refactoring
Sequence:
1. Mevcut behavior'u test'e dök (characterization test)
2. Test geçiyor mu confirm
3. Küçük refactor (5 dk max)
4. Test geçiyor mu? → continue
5. Test fail? → revert
6. Loop küçük adımlarla
Görev: Aşağıdaki fonksiyon için characterization test:
[function]
Test:
- 5 sample input × output (mevcut behavior)
- Edge cases that probably break
- Hidden side effects
Goal: refactor öncesi behavior pin.
Yaygın Refactor Patterns
Extract Function
"Aşağıdaki 100-line fonksiyon. Extract candidates:
[code]
Çıktı:
1. Logical chunk (5-15 line)
2. Pure function olabilir mi?
3. Parametre + return type
4. Naming
5. Refactored code göster
Replace Magic Numbers
const MAX_RETRIES = 3;
const TIMEOUT_MS = 5000;
const CACHE_TTL = 60 * 60; // 1 hour
Replace Conditional with Polymorphism
"Aşağıdaki switch / if-else chain için strategy pattern:
[code]
Çıktı:
- Interface tanımı
- Strategy classes
- Factory
- Client code update
- Test impact
Replace Nested Conditional with Guard Clauses
❌ Before:
function process(user) {
if (user) {
if (user.active) {
if (user.permissions) {
// main logic
}
}
}
}
✅ After:
function process(user) {
if (!user) return;
if (!user.active) return;
if (!user.permissions) return;
// main logic
}
Replace Constructor with Factory
"Replace constructor injection with factory:
[code]
Use case: Multi-tenant, env-specific construction.
"
Legacy → Modern Stack
jQuery → React
"Aşağıdaki jQuery code'u React'e çevir:
[jQuery code]
Adım adım:
1. DOM manipulation → state
2. Event handler → onClick
3. AJAX → fetch / TanStack Query
4. Plugin → React equivalent
5. Animation → CSS / Framer Motion
Migration plan (incremental, not big-bang)."
Class → Functional Component
"Aşağıdaki Class component'i hook'a çevir:
[ClassComponent]
Çıktı:
- componentDidMount → useEffect
- state → useState / useReducer
- componentDidUpdate → useEffect dep
- componentWillUnmount → cleanup
- this.props → destructure
- this.refs → useRef
- Lifecycle order diagram"
REST → GraphQL
"REST endpoint set'i için GraphQL schema:
REST:
- GET /users
- GET /users/:id
- GET /users/:id/posts
- GET /posts/:id/comments
GraphQL:
- Schema tanımı
- Resolver mapping
- N+1 prevention (DataLoader)
- Type generation
- Frontend hooks (React Query equivalent)
"
CommonJS → ESM
"require/module.exports → import/export:
[file]
Çıktı:
- Direct conversion
- Edge cases (dynamic require, __dirname)
- package.json "type": "module"
- Migration order (leaf-first)
"
Database Schema Migration
"Eski schema → modern:
Eski (denormalized):
[schema]
Modern (normalized + indexed):
[hedef]
Migration script:
1. Yeni tablo oluştur
2. Data copy (chunks, no lock)
3. Application read both (transition)
4. Read new only
5. Application write new
6. Drop old
Zero-downtime guarantee.
"
Detay: Veri Analizi
Monolith → Microservice
"Monolith decompose:
Mevcut: 200K LoC monolith, 5 team
Aday split:
- User service
- Order service
- Catalog service
- Notification service
- Analytics service
Her servis için:
1. Boundary (DDD)
2. API contract
3. Data ownership
4. Event-driven communication (Kafka)
5. Deployment (K8s)
6. Migration plan (12-18 ay)
7. Strangler fig pattern
Risk: distributed transaction, latency, complexity.
"
Detay: DevOps + AI
Technical Debt Tracking
"Tech debt inventory:
[codebase scan]
Format:
| Item | Etki | Effort | Risk | Priority |
10 item:
- Outdated dependency
- Test coverage low
- Slow query
- Deprecated API
- Hardcoded config
- Manual deploy
- Memory leak
- Race condition
Quarterly debt budget: 20% engineering capacity.
"
Type Safety Migration (JS → TS)
"JS → TS migration:
Strategy:
1. tsconfig strict false initially
2. Rename .js → .ts incremental
3. Add types leaf-first (utils)
4. Domain models
5. API boundary
6. Component props
7. Strict mode on
8. Cleanup any
Auto codemod:
- ts-migrate
- Bun's TS native
Timeline: 50K LoC = 3-6 ay incremental."
Function Decomposition
"Function 500 line'lık. Decompose:
[function]
Çıktı:
- Single Responsibility violations
- Extract 5-8 smaller function
- Pure vs impure separation
- Test her birini
- Composition (high-level orchestrator)
"
Anti-Patterns Tanıma
"Codebase scan - anti-patterns:
1. God class (1 class 5000 line)
2. Long parameter list (>3)
3. Feature envy (başka class'a aşırı erişim)
4. Data clump (sürekli birlikte geçen 3+ param)
5. Primitive obsession (Value Object yerine string)
6. Switch statement (polymorphism eksik)
7. Lazy class (içeriksiz)
8. Speculative generality (kullanılmayan abstraction)
Her birinin örneği + fix önerisi."
Refactoring Riski
"Refactor öncesi risk değerlendirme:
PR: Extract 3 services from monolith
Risk:
- Behavior change (büyük)
- Test coverage (yetersiz?)
- Production impact (canary?)
- Rollback plan
- Team knowledge gap
- Timeline (3 ay)
Mitigation:
- Feature flag
- Canary deploy %1 → %100
- Both old + new code (transition)
- Monitoring her servis
- Rollback script
- Comm plan stakeholder
"
Detay: Karar Verme
Tool Stack
| Tool | İş |
|---|---|
| Cursor | AI ile incremental refactor |
| GitHub Copilot Workspace | Multi-file refactor |
| Claude (Projects) | Codebase understanding |
| SourceGraph Cody | Large codebase AI |
| JetBrains AI | IDE-integrated |
| Codemod | AST-based transform |
Detay: Cursor IDE
Yaygın Hatalar
- Big-bang refactor: 6 ay, %50 başarısız
- Test eksik: Behavior değişir
- Refactor + new feature: Karışır, rollback zor
- AI önerisine güvenip review yok: Edge case kaybı
- Stakeholder communicate etmemek: Slowdown sürpriz
- Performance regression: Önceden ölçmemek
Sonraki Adımlar
Özet
Refactoring + AI = legacy modernize edilebilir. Test-first + incremental + AI yardım = güvenli. Anahtar: küçük adımlar, sürekli test, business value açık. Rewrite tuzağından kaçın.
Yapay zeka dünyasından haberdar olun
Haftalık özet bültenimize abone olun, en yeni rehberler ve araç incelemeleri direkt e-postanıza gelsin.
İstediğiniz zaman abonelikten çıkabilirsiniz.
Benzer Rehberler

AI ile Veri Analizi: Excel'den Python'a Kadar Pratik Rehber
ChatGPT Code Interpreter, Pandas, SQL, görselleştirme için AI. CSV analiz, dashboard, ML modelleri için pratik.

AI ile Test Yazma: Unit, Integration, E2E için Otomatik Test Üretimi
Copilot, Cursor, ChatGPT ile unit test, integration, E2E test yazma. Jest, Vitest, Playwright örnekleri.

AI ile Mobil Uygulama Geliştirme: React Native, Flutter, Native
AI ile mobil geliştirme: React Native, Flutter, Swift, Kotlin. Copilot, Cursor, optimizasyon.