Engineering Note

You don't always need to stop feature development to improve legacy code. Sometimes, the best time to refactor is while building the next feature.

In a growing Rails application, technical debt rarely comes from one bad decision.

It builds up gradually.

A controller handles too many responsibilities.
A service has business rules nobody wants to touch.
The same logic exists in multiple places.
A small feature requires changes across several unrelated files.

The easy response is to postpone refactoring until there is enough time.

But that time rarely comes.

A more practical approach is to refactor incrementally while shipping features.

For example:
1. Understand the existing flow: Before changing code, identify what the current implementation does and which parts are risky.

2. Improve only what you touch: If a new feature requires changing a large controller, extract the relevant business logic instead of rewriting the entire module.

3. Protect existing behaviour: Add tests around the current flow before changing its implementation.

4. Keep changes small: Avoid combining a feature release with a large structural rewrite. Smaller changes are easier to review, test and roll back.

5. Track recurring debt: If the same area keeps slowing down feature delivery, plan a dedicated refactoring task instead of fixing the same problem repeatedly.

One important distinction:
Not every old piece of code needs refactoring.

Prioritise the code that affects delivery speed, production reliability, security or the cost of future changes.

The goal isn't to make the codebase perfect before shipping the next feature. It's to make sure every new feature doesn't make the codebase harder to maintain.