# Safe Refactoring Standard

## 1. Core Principle

Refactoring means:

```text
Change structure
without unintentionally changing behavior
```

Do not mix large refactoring with unrelated feature development.

---

## 2. Before Refactoring

Inspect:

- Current implementation
- Callers
- Tests
- Routes
- API consumers
- Jobs
- Events
- Commands
- Database dependencies
- Related modules

---

## 3. Establish Baseline

Before major refactoring:

```text
Run existing tests
Inspect current behavior
Record important API behavior
Identify known limitations
```

---

## 4. One Concern at a Time

Prefer:

```text
Controller cleanup
↓
Validate

Service extraction
↓
Validate

Repository extraction
↓
Validate
```

Avoid massive simultaneous restructuring.

---

## 5. Preserve Public Contracts

Do not break existing:

- API routes
- Request formats
- Response formats
- Public URLs
- Database contracts
- Event contracts
- External integrations

unless explicitly required.

---

## 6. Do Not Introduce Abstractions Without Need

Avoid creating:

- Generic repositories
- Generic CRUD layers
- Base service for everything
- Generic event buses
- Unnecessary factories
- Abstraction for abstraction's sake

Create abstractions where they solve a real architectural problem.

---

## 7. Repository Refactoring

Repository should remain responsible for data access.

Do not move business logic into repository merely to reduce service size.

---

## 8. Service Refactoring

Large services should be decomposed by business responsibility.

Prefer:

```text
OrderCreationService
OrderConfirmationService
OrderPaymentService
OrderDeliveryService
```

when responsibilities are genuinely different.

Do not split methods arbitrarily.

---

## 9. Controller Refactoring

Controllers should become thinner.

Move:

```text
Business logic → Service
Query logic → Repository
Validation → Request
Authorization → Policy/Middleware
Response formatting → Resource
```

---

## 10. Regression Protection

After each meaningful refactoring step:

- Run tests
- Review diff
- Compare behavior
- Check API response
- Check affected workflows

---

## 11. Deletion Rule

Never delete existing code merely because it appears unused.

First search:

- References
- Routes
- Jobs
- Commands
- Tests
- External callers

If still uncertain, report before deletion.

---

## 12. Final Refactoring Rule

The result should be:

```text
More maintainable
+
Same expected behavior
+
Better separation
+
No unexplained regressions
```
