AI Prompts for Clean Code: Spotting Spaghetti Code and Avoiding It with Vibe Coding
When you’re dealing with spaghetti code, AI is a powerful tool. We covered the fundamentals in our article Avoiding Spaghetti Code. Here, we’ll walk you through using targeted AI prompts and simple audit scripts to analyze your project for spaghetti code, refactor toward Clean Code and SOLID principles, and write solid unit tests. We’ll also look at vibe coding—a common source of messy, hard-to-follow code.
Vibe Coding and the Spaghetti Code Risk
Vibe coding means rapidly generating code with AI assistants like GitHub Copilot, ChatGPT, or Claude. It works remarkably well for prototypes and small features. The catch: AI optimizes for working code, not maintainability. If you accept every suggestion without scrutiny, you’ll accumulate long functions, duplicated logic, and opaque dependencies.
Spaghetti code doesn’t emerge automatically from vibe coding, but the risk grows sharply if you don’t explicitly ask for Clean Code, SOLID principles, and testable structures. The solution is a workflow combining automatic analysis, clear goals in your prompts, and manual review.
Automatically Auditing Your Project for Spaghetti Code
Before you ask AI for help, you should know where the biggest problems live. A simple Node.js script scans your project for typical warning signs.
// scripts/analyze-spaghetti.js
const fs = require('fs');
const path = require('path');
const TARGET_DIR = process.argv[2] || 'src';
const EXTENSIONS = ['.js', '.ts', '.jsx', '.tsx'];
const issues = [];
function scanDir(dir) {
fs.readdirSync(dir, { withFileTypes: true }).forEach(entry => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) scanDir(full);
else if (EXTENSIONS.includes(path.extname(full))) analyzeFile(full);
});
}
function analyzeFile(file) {
const lines = fs.readFileSync(file, 'utf8').split('\n');
let functionStart = null;
let braceDepth = 0;
lines.forEach((line, index) => {
const trimmed = line.trim();
if (/^\s*(function\s+\w+|const\s+\w+\s*=|async\s+function|=>)/.test(line)) {
functionStart = index;
}
braceDepth += (line.match(/\{/g) || []).length;
braceDepth -= (line.match(/\}/g) || []).length;
if (functionStart !== null && braceDepth === 0 && trimmed === '}') {
const length = index - functionStart;
if (length > 30) issues.push(`${file}:${functionStart + 1} - Function approximately ${length} lines long`);
functionStart = null;
}
if (/^\s*if\s*\(.*\)\s*\{\s*$/.test(line)) {
const next = lines.slice(index + 1, index + 4).join('\n');
const nested = (next.match(/\n\s*if\s*\(/g) || []).length;
if (nested > 0) issues.push(`${file}:${index + 1} - Nested if blocks`);
}
if (/\bvar\b/.test(line)) issues.push(`${file}:${index + 1} - var used`);
const todoMatch = line.match(/(TODO|FIXME|HACK)\b/);
if (todoMatch) issues.push(`${file}:${index + 1} - ${todoMatch[1]} found`);
});
}
scanDir(TARGET_DIR);
if (issues.length === 0) console.log('No obvious spaghetti code indicators found.');
else issues.forEach(i => console.log(i));
This script is deliberately straightforward. For production systems, you’d want to add ESLint, SonarQube, or Codacy on top. But it quickly shows you the hotspots you can tackle with AI.
From Warning to Clean Code
When the script flags a location, paste the affected code into your AI assistant and work through it with the prompts below. The typical workflow looks like this:
- Find the hotspot
- Describe the responsibility
- Use prompts to improve naming, shrink functions, and add tests
- Review the result against Clean Code, SOLID, and OOP standards
- Add unit tests
The sections below provide a ready-to-use prompt for each important area. We’ll distinguish between prompts for individual code blocks and prompts that examine the entire project.
Clean Code Principles and Prompts
We explained the rules in our article Clean Code Principles. When working with AI, it’s crucial to express these rules as concrete objectives in your prompt. Below you’ll find one prompt for each key Clean Code principle.
Meaningful Names
Good names eliminate the need for many comments. Ask AI directly for this, and watch x, data, and tmp disappear.
You are an experienced software developer. Analyze the following code for unclear variable, function, and class names. Suggest a better alternative for each name and explain why the new name improves readability. Ensure names describe intent and responsibility.
Code:
{{CODE}}
Small Functions
Long functions are a hallmark of spaghetti code. Every function should do one thing and ideally fit on a single screen.
You are an experienced software developer. Refactor the following code so each function has at most one responsibility and fits on one screen. Extract helper functions, use descriptive names, and replace deeply nested conditions with early returns or guard clauses. Return the refactored code.
Code:
{{CODE}}
DRY Principle
DRY means Don’t Repeat Yourself. AI often produces duplicated patterns. A prompt finds and eliminates them.
You are an experienced software developer. Identify duplicated logic in the following code and consolidate it into reusable functions, classes, or constants. Explain where DRY was violated and how your solution improves maintainability.
Code:
{{CODE}}
KISS Principle
KISS means Keep It Simple, Stupid. The simplest approach is usually the best.
You are an experienced software developer. Simplify the following code according to the KISS principle. Remove unnecessary abstractions, redundant loops, or convoluted conditions. The code should have the same behavior but be as straightforward and self-explanatory as possible.
Code:
{{CODE}}
Good Comments
Comments should explain the why, not the what. Poor comments mask poor code.
You are an experienced software developer. Review the following code for meaningful comments. Remove redundant or outdated comments, add missing comments that explain the why, and improve the code where it should be self-documenting. Return the revised code.
Code:
{{CODE}}
Consistent Formatting
Consistent formatting reduces cognitive load. This prompt cleans up style and variable declarations.
You are an experienced software developer. Format the following code consistently according to standard conventions. Pay attention to indentation, whitespace, brackets, and line breaks. Avoid var, prefer const and let, and use consistent quote style.
Code:
{{CODE}}
Error Handling
Silent errors, empty catch blocks, and unclear error messages are the spaghetti code of error handling.
You are an experienced software developer. Improve the error handling in the following code. Use meaningful error messages, avoid empty catch blocks, validate input early, and use guard clauses. Return the improved code.
Code:
{{CODE}}
Creating Unit Tests with AI
Unit tests verify the smallest unit of a program in isolation—typically a function or method. They don’t just protect against regressions; they also force you to write testable code. Testable code is almost always better-structured code.
When writing tests, focus on clear Arrange-Act-Assert structure, meaningful test names, and coverage of normal cases, edge cases, and error scenarios. Replace external dependencies like databases or APIs with mocks or stubs.
You are an experienced software developer. Write unit tests for the following code. Use clear Arrange-Act-Assert structure, write meaningful test cases for normal cases, edge cases, and errors. Mock external dependencies and use descriptive test names. Return the test code.
Code:
{{CODE}}
Choosing the Right Prompt for the Job
Different prompts suit different situations. Here’s a quick guide to help you pick the right one.
- Code-detail prompts: Use these for individual functions or files that stand out to you. They work best when you’re actively developing a feature and want to quickly improve readability, naming, or error handling.
- Unit-test prompts: Deploy these right after you refactor a function. Tests lock in behavior and encourage testable design.
- Security audits: Run them before releases, after major changes, or when adding features that process user input.
- Architecture audits: Use these when the project is hard to extend, technical debt is mounting, or you’re planning a refactoring sprint.
- Iterative approach for large projects: Break large codebases into packages, layers, or features. Have the AI analyze each area in turn, then synthesize the findings.
Security Audits with AI
The most reliable way to uncover security flaws in AI-generated code is to work through the project methodically. The prompts below cover different angles.
1. Full Security Analysis
You are an experienced security auditor.
Analyze the entire project for security vulnerabilities.
Look especially for:
- SQL Injection
- Command Injection
- Remote Code Execution (RCE)
- Local File Inclusion (LFI)
- Remote File Inclusion (RFI)
- Path Traversal
- Cross Site Scripting (XSS)
- Cross Site Request Forgery (CSRF)
- Server Side Request Forgery (SSRF)
- Authentication Bypass
- Authorization issues
- Session Hijacking
- Insecure password storage
- Information Disclosure
- Hardcoded Secrets
- Weak cryptography
- Race Conditions
For each vulnerability found, provide:
- Filename
- Line number
- Description
- Attack example
- Risk level (Low/Medium/High/Critical)
- Concrete remediation suggestion
2. Hunting for Hidden Issues
Search only for subtle security problems.
Ignore style and code quality.
Focus on logic flaws an attacker could exploit.
Look especially for:
- Missing authorization checks
- Trust boundary issues
- Unvalidated user input
- Dangerous defaults
- TOCTOU issues
- Privilege escalation
- Authorization bypass
3. Penetration Test from an Attacker’s Perspective
Take the role of a penetration tester.
Try to find only attacks against the application.
For each vulnerability, create:
- Attack scenario
- Example request
- Prerequisites
- Impact
- CVSS assessment
4. Find All User Input Processing
List every place where user input is processed.
Show:
- Input source
- Processing
- Validation
- Escaping
- Database access
- File access
- Shell calls
- Network access
Rate each location for risk.
5. Hunt for Dangerous Functions
Search the entire project for potentially dangerous functions.
Examples:
eval
exec
system
shell_exec
popen
proc_open
passthru
include
require
require_once
fopen
unlink
rename
move_uploaded_file
Check each use for abuse potential.
(You can of course tailor this list to your programming language.)
6. OWASP Top 10
Review the project thoroughly against the current OWASP Top 10.
Create a table:
OWASP Category
affected files
Description
Risk
Recommended measures
7. API Analysis
If the application has APIs:
Analyze all API endpoints.
Check for:
- Missing authentication
- Missing authorization
- IDOR
- Rate limiting
- Mass Assignment
- Injection
- Input Validation
8. “Think Like a Hacker”
This is often my favorite prompt:
Think like an experienced attacker.
Which three vulnerabilities would you exploit first?
Describe step by step:
- why
- how
- likelihood of success
- potential impact
9. Reduce False Positives
Very helpful:
Report only vulnerabilities that are likely actually exploitable.
If you're unsure, flag them explicitly as suspected.
No theoretical or speculative findings.
10. Second Review
After Claude finds something:
Critically review your own analysis.
Look for:
- False positives
- Missed vulnerabilities
- Logic errors
- Further attack vectors
Then produce the final security report.
One Extra Tip
If the project is large (say, thousands of files), start with an architecture overview instead of jumping straight to vulnerability hunting:
First analyze the project's architecture.
Identify:
- Programming language(s)
- Framework(s)
- Authentication
- Database access
- Upload functions
- Admin areas
- API endpoints
- File operations
- External dependencies
Then create a plan for a complete security audit and carry it out step by step.
This gives Claude a better overview and often leads to more thorough results than a single “check everything” prompt. That said, an LLM audit doesn’t replace specialized tools (SAST, dependency, or DAST scanners)—it complements them. Best results come from combining both.
Equally important is reviewing the architecture across the project. Single prompts like “Check for SOLID” usually deliver only generic advice. You’ll get better results with targeted audits.
Architecture, Clean Code, and SOLID Audits
The prompts below help you review the entire project for maintainability, duplicated logic, and SOLID/OOP principles. They complement the code-detail prompts from the previous section and examine the project as a whole.
1. Complete Architecture Review
You are an experienced software architect.
Analyze the entire project for:
- Clean Code
- OOP
- SOLID
- DRY (Don't Repeat Yourself)
- KISS
- YAGNI
- Separation of Concerns
- High Cohesion
- Low Coupling
Start by mapping out the overall architecture.
Then identify every location that violates these principles.
For each issue, provide:
- File
- Class
- Method
- Description
- Reasoning
- Improvement suggestion
- Priority (Low/Medium/High)
2. Finding Duplicate Logic (My Favorite)
This is exactly what you described.
Scan the entire project for duplicate logic.
Look specifically for:
- identical functions
- nearly identical methods
- copy-pasted code
- duplicate business logic
- calculations implemented multiple times
- repeated validation logic
- multiple database access patterns
- redundant API calls
For each match, show:
- both files
- both methods
- similarity percentage
- which method should become the shared foundation
- how to consolidate the duplicates
Ignore variable name differences.
3. Checking SOLID Principles Individually
Review each class against the SOLID principles.
For every class, answer:
Single Responsibility:
Does the class have more than one reason to change?
Open/Closed:
Is code being modified instead of extended?
Liskov:
Are inheritance hierarchies correct?
Interface Segregation:
Are interfaces too broad?
Dependency Inversion:
Are concrete classes used instead of abstractions?
Provide concrete refactoring suggestions.
4. Classes with Too Many Responsibilities
Hunt for God Classes.
Recognize them by:
- over 500 lines
- many methods
- awareness of many other classes
- mixing business logic, UI, and database access
- numerous member variables
Propose a sensible decomposition.
5. Problem Methods
Find methods that violate Clean Code.
Examples:
- over 30 lines
- multiple responsibilities
- deep nesting
- many parameters
- multiple boolean flags
- duplicated logic
Suggest refactoring approaches.
6. Checking Responsibilities
Analyze each class.
Describe its actual responsibility in one sentence.
If a class has multiple responsibilities,
list them explicitly.
Then propose a sensible split.
7. Dependencies
Create a dependency diagram of the project.
Highlight:
- circular dependencies
- unnecessary dependencies
- tight coupling
- Dependency Inversion violations
Suggest improvements.
8. Reviewing Inheritance
Analyze all inheritance hierarchies.
Check for:
- unnecessary inheritance
- should composition be used instead?
- Liskov violations
- duplicate implementations
Suggest better alternatives.
9. Refactoring Plan
This is often the most useful prompt.
Create a complete refactoring roadmap.
Order all issues by priority.
For each issue, describe:
- why it exists
- which SOLID rule is violated
- how the class should look after refactoring
- which files are affected
- effort (small/medium/large)
Goals:
- less code
- no duplicate logic
- better maintainability
- better testability
10. Strict Architecture Review
Act as a Senior Software Architect conducting a code review.
Be critical.
Accept no duplicate logic.
Accept no classes with multiple responsibilities.
Accept no copy-and-paste solutions.
Show every location you would force to change before merging to main.
Prioritize the most critical issues first.
One More Tip
If your project is already substantial (for example, over 20,000 lines of code), you can give Claude Code this additional task:
Work iteratively.
Go through file by file.
After each file, create a list of problems found.
Summarize all results at the end.
When you discover similar methods across different files, compare them and check whether they should be consolidated into a shared function or base class.
Explicitly search for DRY violations and duplicate business logic implementations.
That last instruction is particularly important: by default, Claude evaluates files in isolation. By explicitly asking it to search across files for identical or similar logic, it detects duplicate implementations and consolidation opportunities far more reliably.
Example Workflow for a Refactoring Session
Imagine you’re taking over a project full of AI-generated code. A typical workday might look like this:
- Run
node scripts/analyze-spaghetti.js srcand gather the hotspots. - Feed the most problematic functions into code-detail prompts for naming, formatting, and error handling.
- Generate unit tests for the refactored sections.
- When you spot duplicates or oversized classes across file boundaries, launch the architecture audits.
- Build a refactoring plan and work through it by priority.
- Before merging or releasing, run security audits.
- Review all AI suggestions manually. AI helps you find problems, but you decide the solution.
Conclusion
AI and vibe coding are powerful tools when you know the right questions to ask. The best results come from first identifying spaghetti code with a simple script, then cleaning it up with targeted prompts focused on Clean Code, SOLID, OOP, and unit tests. That way, AI remains an accelerator for code quality instead of a liability.
Book Recommendations
These books guide you through Clean Code and professional software development.
Software Engineering
Books about software quality, clean code, code reviews and software development processes
Clean Code: A Handbook of Agile Software Craftsmanship von Robert C. Martin
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
The Pragmatic Programmer: Your Journey to Mastery von David Thomas, Andrew Hunt
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
Related Articles
- Avoiding Spaghetti Code
- Clean Code Principles
- Clean Code and SOLID Principles
- SOLID Principles Fundamentals
- Unit Testing Fundamentals
- Error Handling and Debugging




