Ad Space (horizontal)
Use Cases

Cara Mengotomatisasi Refactoring dengan Claude Code

Pelajari cara mengotomatisasi code refactoring secara efisien menggunakan Claude Code. Dilengkapi prompt praktis dan pola refactoring konkret untuk project nyata.

Mengapa Refactor dengan Claude Code?

Semua orang tahu refactoring itu penting, tapi melakukannya secara manual itu membosankan dan sering diprioritaskan belakangan. Claude Code memahami seluruh project-mu dan bisa mengeksekusi refactoring secara otonom di banyak file sekaligus.

Pola 1: Meningkatkan Type Safety

Menghilangkan Tipe any

> Search the project for all any types and replace them with proper types.
> After the changes, verify that npx tsc --noEmit passes.

Berikut cara Claude Code menanganinya:

  1. Mencari file yang berisi tipe any
  2. Menyimpulkan tipe yang tepat dari kode di sekitarnya
  3. Membuat file definisi tipe jika diperlukan
  4. Menjalankan type checker untuk memverifikasi semuanya bisa di-compile

Sebelum dan Sesudah

// Sebelum
function processData(data: any): any {
  return data.items.map((item: any) => item.name);
}

// Sesudah
interface DataPayload {
  items: Array<{ name: string; id: number }>;
}

function processData(data: DataPayload): string[] {
  return data.items.map((item) => item.name);
}

Pola 2: Memecah Fungsi dan Memperjelas Tanggung Jawab

Memecah fungsi yang terlalu besar adalah sesuatu yang Claude Code tangani dengan sangat baik.

> The createOrder function in src/services/orderService.ts is over 200 lines.
> Split it into smaller functions following the single responsibility principle.
> Make sure existing tests still pass.

Prompt untuk Pemecahan

> Split the function using these guidelines:
> - Each function should be 30 lines or fewer
> - Separate validation, business logic, and persistence
> - Add JSDoc comments to each function
> - Split tests to match the new function boundaries

Pola 3: Menstandarkan Error Handling

Seragamkan pola error handling di seluruh project.

> Standardize error handling across the project:
> - Use a custom error class (AppError)
> - Define error codes as constants
> - Always include logging in try-catch blocks

Berikut contoh yang dihasilkan Claude Code:

// src/errors/app-error.ts
export class AppError extends Error {
  constructor(
    public readonly code: string,
    message: string,
    public readonly statusCode: number = 500,
    public readonly cause?: Error
  ) {
    super(message);
    this.name = 'AppError';
  }
}

// Konstanta kode error
export const ErrorCodes = {
  USER_NOT_FOUND: 'USER_NOT_FOUND',
  INVALID_INPUT: 'INVALID_INPUT',
  DB_CONNECTION_ERROR: 'DB_CONNECTION_ERROR',
} as const;

Pola 4: Menambah dan Memperbaiki Test

Tambahkan test di area yang coverage-nya kurang.

# Gunakan laporan coverage untuk memandu penambahan test
npx vitest run --coverage | claude -p "Identify files with low coverage and add the missing test cases"
> Bring test coverage for everything under src/services/ to at least 80%.
> Cover not just happy paths, but also edge cases and error scenarios.

Pola 5: Menstandarkan Format Respons API

> Standardize all API endpoint responses to this format:
>
> Success: { success: true, data: T }
> Failure: { success: false, error: { code: string, message: string } }
>
> Update the frontend code to match the new format.

Tips untuk Refactoring yang Aman

1. Verifikasi Test Terlebih Dahulu

> Run npm test first and make sure all existing tests pass.
> If any tests are failing, report them before making changes.

2. Kerjakan Secara Bertahap

Refactor modul per modul daripada semuanya sekaligus.

> Start by refactoring only src/services/userService.ts.
> Verify that tests pass after the changes before moving on.

3. Review Diff-nya

> Show me the git diff. If it's too large, summarize the changes by file.

4. Gunakan Branch Terpisah

git checkout -b refactor/error-handling
claude
> Start the error handling refactoring...

Contoh Nyata: Modernisasi Legacy Code

Berikut cara memodernisasi codebase lama secara bertahap:

> Modernize this project with the following changes:
> 1. Replace var with const/let
> 2. Convert callback functions to async/await
> 3. Convert require to import
> 4. Verify tests pass after each change
> 5. Proceed one step at a time and report results at each stage

Kesimpulan

Dengan Claude Code, refactoring yang biasanya memakan waktu berhari-hari bisa diselesaikan dalam hitungan jam. Kuncinya adalah: berikan aturan yang spesifik, kerjakan secara bertahap, dan selalu validasi dengan test. Mulai dengan modul kecil dan lihat sendiri hasilnya.

Ad Space (rectangle)
#Claude Code #refactoring #code quality #automation #TypeScript