🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Practical Exercise: Refactoring

Test your architectural skills. Practice generating AI-driven safety nets (tests), enforcing the Single Responsibility Principle, and translating cryptic legacy syntax into self-documenting code.

Narrated Video Summary
data-composition-id="aisoftwareengineering-exercise-refactoring"1280×720 @ 30fps6 clips2:35 total

Exercise 2: Legacy Refactoring

Refactoring legacy code manually is terrifying because you might break a hidden dependency. In this exercise, you are presented with a massive 500-line monolithic function that mixes database queries, business logic, and UI rendering. Your objective is to use AI to safely split this monolith into atomic, testable functions without altering the core business logic. We call this 'Surgical Refactoring'.

// The Monolith:
async function doEverything(req) {
  // 50 lines of Auth verification
  // 100 lines of complex SQL queries
  // 200 lines of data formatting
  // 150 lines of HTML rendering
}

// Objective: Break this apart safely.

The Safety Net (TDD)

Rule #1 of AI Refactoring: NEVER refactor without tests. If you ask the AI to rewrite a 500-line function, it might hallucinate and drop a critical business rule. Therefore, Step 1 is NOT refactoring. Step 1 is generating a test suite for the current, ugly legacy code. Use the prompt: 'Analyze this legacy function. Generate a comprehensive Jest test suite that captures its current behavior and edge cases.'

// Step 1: Secure the perimeter.
Prompt: "@legacy.ts 
Generate a Jest suite capturing the exact current 
behavior of `doEverything()`. Do NOT change the code."

Executing the Split

Once the tests are Green, you can execute the refactor. Command the AI: 'Refactor `doEverything()`. Split it into atomic functions based on the Single Responsibility Principle (SRP). Maintain the exact same inputs and outputs. Ensure it passes the generated test suite.' The AI will break the monolith into modular pieces. If the tests turn Red, the AI hallucinated. If they stay Green, the refactor is mathematically verified.

// Step 2: The Refactor
Prompt: "Refactor this monolith into atomic functions. 
Ensure all current tests continue to pass."

// AI generates modular code.
// Run tests -> 🟢 PASS. Refactor is safe.

Self-Documenting Code

Legacy code is usually filled with cryptic variable names like `let data = q_res.x`. As a final polish step, you must use AI to make the code self-documenting. Use Inline Edit (Ctrl+K) on the newly refactored code: 'Rename all variables to be highly descriptive of their business purpose. Add JSDoc comments to the new atomic functions.' The AI will transform `data` into `customerPurchaseHistory`.

// ❌ Legacy Naming:
const c = r.filter(x => x.a > 18);

// ✅ Refactored Naming (via AI):
const adults = users.filter(user => user.age > 18);

Exercise Complete

You have successfully completed the Legacy Refactoring exercise. You understand that refactoring without tests is reckless, and that AI is the ultimate tool for generating both the safety net and the surgical logic extraction. We have one final exercise: Autonomous Debugging.

/* Legacy Code Eliminated */
.refactor { next: 'exercise_debugging'; }
0:00 / 2:35
Scene 1 / 6 — Exercise 2: Legacy Refactoring
Total XP: 0|💻 aisoftwareengineering XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Exercise 2

Refactor Legacy.

Quick Quiz //

What is the absolute FIRST step you must take before asking an AI to rewrite a massive legacy function?


🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Legacy code is a liability. However, touching legacy code without a safety net is suicidal. Learn how to use AI to safely dismantle monolithic logic.

1The AI Safety Net

Before you change a single line of a legacy monolith, you must map its behavior. Use the Composer to target the massive file and prompt: 'Analyze this file. Write a comprehensive Jest suite that tests its current behavior exactly as it is, including all its weird edge cases.' The AI will generate tests. Run them. When they are Green, you have established a deterministic perimeter around the legacy code.

+
Prompt: "Generate unit tests for monolithic logic."
// Jest suite captures edge cases and database connections
localhost:3000
localhost:3000
Behavior mapped: Monolith perimeter verified. 8 specs pass under test.

2The Surgical Split

With tests passing, you can command the AI to refactor. Prompt: 'Refactor this function. Split the database calls, the business logic, and the UI rendering into separate, atomic functions. Ensure the main function signature remains identical so we don't break external dependencies.' The AI will rewrite the code. Run the tests. If they turn Red, feed the error trace back to the AI until they are Green.

+
Prompt: "Split handleRequest monolith into atomic functions."

// AI separates query from parsing layer
localhost:3000
localhost:3000
Refactored modular logic: doEverything() uses helper modules. Tests stay green.

3Self-Documenting Polish

Legacy code is famous for variables like const a = 1;. This is hostile to human readers. Use Inline Edit (Ctrl+K) on the newly modularized code and command: 'Refactor all variable and function names to be highly descriptive. Add standard JSDoc comments to every function.' The AI will transform the codebase into a clean, modern, self-documenting architecture.

+
Ctrl+K: "Rename variables descriptively. Add JSDoc comments."

// clean, self-documenting naming
localhost:3000
localhost:3000
Variables Polished: clientPurchaseTotal used. Documentation generated correctly.

4Step-by-Step Breakdown

Exercise 2: Legacy Refactoring. Refactoring legacy code manually is terrifying because you might break a hidden dependency. In this exercise, you are presented with a massive 500-line monolithic function that mixes database queries, business logic, and UI rendering. Your objective is to use AI to safely split this monolith into atomic, testable functions without altering the core business logic. We call this 'Surgical Refactoring'.

The Safety Net (TDD). Rule #1 of AI Refactoring: NEVER refactor without tests. If you ask the AI to rewrite a 500-line function, it might hallucinate and drop a critical business rule. Therefore, Step 1 is NOT refactoring. Step 1 is generating a test suite for the current, ugly legacy code. Use the prompt: 'Analyze this legacy function. Generate a comprehensive Jest test suite that captures its current behavior and edge cases.'

Before commanding an AI to refactor a massive, undocumented legacy function, what must you do first?

  • Delete the function.
  • Command the AI to generate a comprehensive test suite that captures the function's CURRENT behavior to serve as a safety net against hallucinations.

Executing the Split. Once the tests are Green, you can execute the refactor. Command the AI: 'Refactor doEverything(). Split it into atomic functions based on the Single Responsibility Principle (SRP). Maintain the exact same inputs and outputs. Ensure it passes the generated test suite.' The AI will break the monolith into modular pieces. If the tests turn Red, the AI hallucinated. If they stay Green, the refactor is mathematically verified.

Self-Documenting Code. Legacy code is usually filled with cryptic variable names like let data = q_res.x. As a final polish step, you must use AI to make the code self-documenting. Use Inline Edit (Ctrl+K) on the newly refactored code: 'Rename all variables to be highly descriptive of their business purpose. Add JSDoc comments to the new atomic functions.' The AI will transform data into customerPurchaseHistory.

What is the primary benefit of using AI to rename variables and extract logic into smaller functions during a refactor?

  • It makes the code execute faster in the CPU.
  • It creates 'Self-Documenting Code', drastically improving readability and making the system easier for future human developers to maintain.

Exercise Complete. You have successfully completed the Legacy Refactoring exercise. You understand that refactoring without tests is reckless, and that AI is the ultimate tool for generating both the safety net and the surgical logic extraction. We have one final exercise: Autonomous Debugging.

Refactor Real Duplicated Logic. Finish extracting the discount calculation into one clean, reusable function.

Level Up 🚀

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Semantic Usage

Using the proper structure for Exercise 2: Legacy Refactoring ensures that screen readers can correctly interpret the content hierarchy and purpose.

<!-- Apply semantic elements appropriately -->

SEO Implications

  • 1

    Contextual Relevance

    Proper implementation of Exercise 2: Legacy Refactoring provides search engine crawlers with better context, improving the indexing accuracy of your page.

Best Practices

Clean Code

Always validate your structure when using Exercise 2: Legacy Refactoring to prevent layout shifts and DOM inconsistencies.

Separation of Concerns

Keep styling and behavior separate from the structural markup of Exercise 2: Legacy Refactoring.

Frequent Bugs

THE BUG

Unexpected layout shifts or styling failures.

THE FIX

Ensure all implementations related to Exercise 2: Legacy Refactoring are properly structured according to strict specifications.

Real-World Examples

Production Usage

Here is how Exercise 2: Legacy Refactoring is typically implemented in a professional, robust application.

<!-- Best practice implementation of Exercise 2: Legacy Refactoring -->
<div class="production-ready">
  <!-- Content -->
</div>

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Not reading error messages carefully

Uncaught TypeError: Cannot read properties of undefined (reading 'length') // Solution: Ensure the variable you are calling .length on is initialized as a string or an array, not undefined.

The Solution //

Most of the time, the compiler or interpreter tells you exactly what line caused the crash and why. Read stack traces from the top down to identify the root cause.

The Error //

Hardcoding sensitive credentials

// Wrong const API_KEY = 'sk-123456789'; // Correct const API_KEY = process.env.API_KEY;

The Solution //

Never hardcode API keys, passwords, or secrets in your source code. Use environment variables (.env files) to keep them secure and out of version control.

Lesson Glossary

[01]Legacy Code

Old, usually undocumented code that developers are afraid to touch because they don't know what it breaks.

Code Preview
The Liability

[02]Safety Net

A comprehensive suite of unit tests written BEFORE refactoring to ensure existing behavior is not broken.

Code Preview
The Cage

[03]Monolith

A massive, single function or file that handles multiple distinct responsibilities (DB, UI, Logic) at once.

Code Preview
The Spaghetti

[04]Atomic Function

A small, modular function that does exactly one thing, making it highly testable and readable.

Code Preview
The Building Block

[05]Function Signature

The exact name, parameters, and return type of a function. Must remain identical during an internal refactor.

Code Preview
The API Contract

Continue Learning