← Back to Learn
AdvancedIntermediate12 min read

Refactoring AI Spaghetti

Identify and fix the telltale signs of LLM-generated code: repetition, verbosity, and over-documentation.

AI models are trained to be helpful, which often means they are overly verbose. They explain the obvious, repeat patterns unnecessarily, and write "safe" code that lacks elegance.

The Symptoms

1. The "Try-Catch" Everything

AI loves to wrap everything in a try-catch block, even when it's not needed or when the error handling is just console.log(error).

**AI Code:**

javascript
async function getData() {
  try {
    const response = await fetch('/api/data');
    const json = await response.json();
    return json;
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
}

**Human Refactor:**

javascript
// Let the caller handle errors, or use a global boundary
const getData = async () => 
  (await fetch('/api/data')).json();

2. The Comment Echo

AI often writes comments that just repeat what the code says.

**AI Code:**

python
# Increment i by 1
i = i + 1

# Check if user is valid
if user.is_valid:
    return True

**Human Refactor:**

python
i += 1

if user.is_valid:
    return True

*(No comments needed. The code speaks for itself.)*

3. Structural Repetition

AI models are autocomplete engines. Once they start a pattern, they stick to it, even if it leads to redundancy.

**AI Code:**

css
.header { margin: 10px; padding: 20px; color: blue; }
.footer { margin: 10px; padding: 20px; color: blue; }
.sidebar { margin: 10px; padding: 20px; color: blue; }

**Human Refactor:**

css
.container { 
  margin: 10px; 
  padding: 20px; 
  color: blue; 
}

The Cure

Refactoring AI code is about **subtraction**.

Remove obvious comments.
Flatten nested logic.
Extract repeated logic into functions (DRY principle).
Trust the reader's intelligence.

Up Next

Humanizing Your LLM Prompts

Read Guide →
Vibe Code Detector