AI Powered Software Development
November 17, 2026 2 min read

Prompting for Refactoring

HS
HEMANT SINGH
Technical Writer & Educator

What is Code Refactoring?

Code refactoring means improving the internal structure of existing code without changing its external behaviour.

In simple terms:

  1. The code should become cleaner.
  2. The code should become easier to understand.
  3. Duplicate code should be reduced.
  4. Maintenance should become easier.
  5. Existing functionality should continue working.

Important: Refactoring is not the same as adding new features or fixing bugs.

Consider this example.

Before refactoring:

<?php

function calculatePrice($price, $quantity) {
$total = $price * $quantity;

if ($total > 1000) {
$total = $total - ($total * 10 / 100);
}

return $total;
}

The code works, but it has some weaknesses:

  1. No type declarations.
  2. No return type.
  3. No strict typing.
  4. The discount calculation is embedded in the function.
  5. Variable names could be more descriptive.

After refactoring:

<?php

declare(strict_types=1);

function calculatePrice(
float $price,
int $quantity
): float {

$total = $price * $quantity;

if ($total > 1000) {
$total = applyDiscount($total, 10);
}

return $total;
}

function applyDiscount(
float $amount,
float $discountPercentage
): float {

$discount = ($amount * $discountPercentage) / 100;

return $amount - $discount;
}


Advanced technique: Refactoring without breaking functionality

This is one of the most important techniques for professional developers.

Suppose your existing application has a fee calculation system.

You want to improve its code, but you cannot afford to change how student fees are calculated.

Use this prompt:

Refactor the existing student fee calculation module.

Critical requirements:

1. Preserve all existing fee calculations.
2. Preserve admission fee rules.
3. Preserve examination fee rules.
4. Preserve discounts and concessions.
5. Preserve existing database relationships.
6. Do not change the output format.

Before refactoring:
- Analyze all related methods.
- Identify dependencies.
- Identify existing tests.
- Identify potential risks.

After refactoring:
- Run all related tests.
- Compare old and new calculation results.
- Test normal and edge cases.
- Report any behaviour differences.

Do not proceed with risky changes without approval.