Skip to main content

Claude Prompt to Reduce Code Complexity

Cut cyclomatic complexity and nested conditionals with early returns and guard clauses, plus before/after diffs and verified behavior preservation.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt

                                

What this prompt does

This prompt takes a block of code you already know is too tangled and systematically dismantles the complexity — not by rewriting it arbitrarily, but by applying exactly the techniques that address the specific issues you call out in [perceived_issues]. The eight simplification strategies are listed explicitly in the template so the AI cannot hallucinate a solution that trades one form of complexity for another (replacing deep nesting with an AbstractFactoryBuilder is a classic LLM mistake this template blocks by name).

The before/after structure with cyclomatic complexity counts per change is what separates this from a generic "clean up my code" request. You get measurable evidence the simplification worked, not just a style preference. The [test_instruction] slot lets you enforce that the AI must verify behavior — whether that means referencing your existing test suite, generating assertions, or confirming edge cases by inspection.

The [target_complexity] and [max_params] variables force you to state your own quality bar upfront. This matters because "simpler" means different things in a 10-line utility function versus a 200-line controller method.

When to use it

  • A code review flags a method with cyclomatic complexity above 10 and you need a clear refactor path.
  • You inherited a legacy PHP controller or JavaScript callback hell that nobody wants to touch.
  • A pull request is blocked because a senior engineer asked you to "extract that conditional" but you are not sure which pattern fits.
  • You are about to add a feature to a function that already has five nested if/else branches and you want to clean first.
  • You wrote something under deadline pressure that works but you know you will regret reading in three months.

Example output

For a PHP method with a five-level nested conditional checking user permissions and subscription status:

Before: cyclomatic complexity 11
After:  cyclomatic complexity 4

Change 1 — Guard clauses at entry
Before: if ($user) { if ($user->active) { if ($user->subscription) { ... } } }
After:  if (!$user || !$user->active || !$user->subscription) { return null; }
Why: flattens three nesting levels into a single exit point; behavior identical for all falsy paths.

Change 2 — Extracted method: hasValidAccess()
Before: inline boolean expression spanning 14 tokens
After:  $this->hasValidAccess($user, $resource)
Why: names the intent; cyclomatic complexity moves to a testable unit.

Pro tips

  • Fill [perceived_issues] with specific line numbers or symptoms ("lines 14-30 have four nested ifs, and the loop at line 40 rebuilds the same array three times") — vague descriptions produce vague refactors.
  • Set [max_params] to 3 for most codebases; bump to 4 only for framework callbacks where the signature is dictated externally.
  • Set [test_instruction] to "reference our PHPUnit tests in tests/Unit/OrderTest.php and confirm each assertion still holds" rather than leaving it blank — this turns the AI into an accountable reviewer, not a guesser.
  • Run the refactored output through your actual static analysis tool (PHPStan, ESLint, Pylint) before merging — cyclomatic complexity estimates from LLMs are directionally correct but not always precise.
  • If the AI applies polymorphism or a strategy pattern when you just wanted early returns, that is the over-abstraction warning in the template firing late — re-run with [perceived_issues] explicitly saying "no design patterns, just flatten the control flow."

Frequently Asked Questions

Will the prompt change my function's public API or return types?
The template includes an explicit constraint — 'Maintain the same public API' — so the AI is instructed not to rename public methods, change signatures, or alter return types. Internal helpers it extracts will be private by default. If you need the API to change as part of the refactor, remove that constraint and state it in [perceived_issues].
What should I put in [target_complexity] if I don't know what cyclomatic complexity my code has?
Run your language's built-in tool first: phploc or phpmd for PHP, radon for Python, eslint with the complexity rule for JavaScript. Anything above 10 per function is the common threshold for 'needs attention.' Set [target_complexity] to 5 or 6 for methods that will be unit-tested heavily, 8-10 for integration-layer code where some branching is unavoidable.
The AI simplified my code but I'm not sure the edge cases are still handled. What do I do?
This is exactly what [test_instruction] is for. Fill it with a concrete instruction like 'list every null, empty, and out-of-range input the original code handled and confirm the refactored version handles each identically.' If you have existing tests, paste the test method names and ask the AI to trace execution through the new code for each one. Do not skip this step for any code that handles money, auth, or data writes.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in AI Coding Assistants

Engr Mejba Ahmed

Engr Mejba Ahmed

Claude Code Expert · Online

👋

Hey there!

Quick Actions

WhatsApp Instant reply

Chat on WhatsApp

+880 1723 741224 · Instant reply

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

[email protected]

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support