AI has been widely adopted in software development for some time now. It’s a decent tool for creating new code, but when it comes to refactoring, I believe, there’s a fundamental flaw…

AIs work as statistical models, meaning they provide the most probable outcome. This approach works well when creating something new. But when I refactor my code, I need to be absolutely sure that the code transformation won’t change the code behaviour. Otherwise, I end up not with a refactoring but with new behavior - whether better or worse. So I need 100% certainty that the refactor is actually a refactor, and this is something an AI cannot provide, unless the code is 100% covered by tests - which is a whole different topic that I won’t develop for now.

So does this make AI unsuitable for refactoring? Well, yes and no. I won’t use an AI tool to perform the refactoring itself, but there’s something else that AI can do for refactoring that has been a pain point for me.

Whenever I refactor code, the hardest thing is to guess what the final code shape will be. I know perfectly well what I want from the code beforehand - I want to make something new possible, like an easier way to introduce a feature or a bug to become easily fixable. In other words:

For each desired change, make the change easy (warning: this may be hard), then make the easy change. Kent Beck (Source)

Since I rarely know (or should I say “knew” by now…) the final shape of the code, each refactoring step is a small “leap of faith” that I believe will lead me towards “make the easy change”. But that’s not necessarily true, which leads to a pretty significant amount of rework and dropped commits, if not entire branches, while trying to find the destination by guessing the paths.

But if we look at the problem from the destination perspective, the “easy change” should be pretty obvious before refactoring - otherwise, why would one refactor at all? And that “easy change” can be easily expressed in human language, like “I want to be able to add new components here with one line of code.” The problem is that we don’t know the code expression for this.

And this is where AI comes into play - it can generate these code shapes as directions toward which the code could be refactored. I use prompts like this to get possible destinations:

```tsx
// code here
```

Here's my login modal code written in React. You can see that adding new steps is quite hard and requires a lot of code. Propose 5 ways to refactor this to make adding new steps simple, ideally with just one line.

I choose the code shape I prefer, now that I have my destination, and I can refactor with small, safe steps towards the desired destination. In the end, my result may not be exactly the one proposed by AI (some ideas may spark along the way…), but having the code shape (not the code itself, that is a detail) that I want the code to look like has been extremely helpful in my software adventures.