Labs ICT
โญ Pro Login

Code Refactoring Techniques

Safely improve code structure without changing behavior.

Code Refactoring Techniques

Refactoring is the process of restructuring existing code without changing its external behavior. The goal is to improve code readability, reduce complexity, and make it easier to maintain.

When to Refactor


  CODE SMELL INDICATORS
  =====================

  +------------------------------------------+
  | Warning Signs You Need to Refactor:      |
  +------------------------------------------+
  |                                          |
  | - Code duplication (DRY violation)       |
  | - Long functions (> 30 lines)            |
  | - Large classes (> 300 lines)            |
  | - Deep nesting (> 3 levels)              |
  | - Magic numbers/strings                  |
  | - Long parameter lists (> 3 params)      |
  | - Dead code (unused variables/functions) |
  | - Complex conditionals                   |
  | - Comments explaining "why"              |
  | - God objects (doing everything)         |
  |                                          |
  +------------------------------------------+

Common Refactoring Techniques


  EXTRACT METHOD
  ==============

  Before:
  function processOrder(order) {
    // validate order (20 lines)
    // calculate total (15 lines)
    // apply discounts (10 lines)
    // save to database (10 lines)
    // send confirmation email (15 lines)
  }

  After:
  function processOrder(order) {
    validateOrder(order);
    const total = calculateTotal(order);
    applyDiscounts(order, total);
    saveOrder(order);
    sendConfirmation(order);
  }

  Each method does ONE thing well.

Extract Variable


  Before:
  if (user.age > 18 && user.hasID && user.balance > 0) {
    // ...
  }

  After:
  const isAdult = user.age > 18;
  const hasValidID = user.hasID;
  const hasFunds = user.balance > 0;

  if (isAdult && hasValidID && hasFunds) {
    // ...
  }

Replace Magic Numbers


  Before:
  if (status === 3) { ... }
  for (let i = 0; i < 86400; i++) { ... }

  After:
  const STATUS_APPROVED = 3;
  const SECONDS_IN_DAY = 86400;

  if (status === STATUS_APPROVED) { ... }
  for (let i = 0; i < SECONDS_IN_DAY; i++) { ... }

Refactoring Rules

  • Always have tests before refactoring
  • Make small changes and test after each one
  • Don't refactor and add features at the same time
  • Use your IDE's refactoring tools when available
  • Commit frequently so you can revert if needed

Key Takeaways

  • Refactoring improves code without changing behavior
  • Watch for code smells as refactoring signals
  • Extract methods, variables, and replace magic numbers
  • Always refactor with tests in place

๐Ÿงช Quick Quiz

What is Refactoring?