logoalt Hacker News

The Economic Benefit of Refactoring

155 pointsby javaeeeeetoday at 3:10 PM73 commentsview on HN

Comments

Viliam1234today at 5:38 PM

I find it funny how the best practices for programmers, ignored in most IT companies, get reinvented as the best practices for AIs.

Boring: The documentation should be in code, not in external Word documents uploaded to the company SharePoint server.

Exciting: The documentation for the AI should be in code, not in external Word documents uploaded to the company SharePoint server.

Boring: You should give your developers the big picture of the project, not just micromanage them using Jira tasks.

Exciting: You should give your AI the big picture of the project in CLAUDE.md, not just micromanage it using prompts.

Boring: Refactoring makes your developers more productive in long term.

Exciting: Refactoring makes your AI more productive in long term.

show 3 replies
whats_a_quasartoday at 5:29 PM

This is such a nice piece, this is how people should write about AI. Specific, grounded to how the tools are actually being used, and quantitative. There is so much bad AI commentary that is incredibly vague, divorced from any actual use cases, or written by people who don't actually use the tools. It is good to see a critique that is "here is a thing AI is bad at and measurements to show it" rather than gesturing "here is why I think AI is problematic for society."

It is rather different but another piece of research I liked for the same reason was this report that interviewed Boko Haram members about how they used AI to assist terrorism. You get these interminable online debates that are so unproductive and reporting that is specific is such a breath of fresh air.

https://casp.ac/reports/ai-enabled-terrorism

show 1 reply
firasdtoday at 4:18 PM

I think this is one of those things where a human in the loop is indispensable

An agentic refactoring pass does make sense cause one LLM reviewing work can spot things the ‘generator’ LLM missed while focused on the initial task output

But can the reviewer agent ever actually have in mind what this project actually is? And how the code all comes together to do the work involved? In other words what parts of the code are redundant or can be made more elegant

Asking coding agents to refactor your codebase is maybe like asking trauma surgeons to increase your exercise capacity. The agents are gonna need a really holistic POV to do this properly

I guess part of my point is that just splitting big files into multiple files is only refactoring in a superficial sense without having a theory of what code belongs together and what can be extracted into utility functions etc. Is splitting files actually like decomposing factors or is it like splitting a larger number into smaller numbers that still eventually get added together

A good example of what I mean is that agents often don’t ~actually~ understand the whole system anyway. They might implement a system to store and calculate something that is already being fetched via API. Humans often have a dual perspective — a holistic sense of the project and (when applying our mind to a task) a precise scalpel: ‘oh if we just look at this this JSON it has a key with this data already’

show 3 replies
BenoitEssiambretoday at 4:25 PM

The benefits go beyond reducing token consumption. Compact contexts also foster better reasoning, enable intelligence across more layers if you can load them in a single context, and writing software to enable this, results in more correct software, software that _generalizes_, that has higher probability of being correct not just for tested cases, but for the interpolations and extrapolations of these cases.

Refactoring towards good abstractions is more powerful than people realize. There's information theoretic bayesian math to back this up.

It's a bit of a divine coincidence that software that is more economically and energy efficient to process and run tends to also be more correct.

It's all about reducing the entropy of your code. https://benoitessiambre.com/entropy.html

show 2 replies
pmg101today at 3:56 PM

It's very interesting to have some data on this.

It matches my experience which is that LLMs greatly benefit from well factored code, but are not particularly adept at creating such code.

Much like most human developers I suppose!

show 2 replies
nycticoraxtoday at 8:53 PM

This is interesting, but I think it would be even more interesting to see a comparison of the token cost of adding a new feature, in the original codebase vs the refactored one. You'd think/hope that the cost of adding the new feature would be lower when starting from the refactored codebase, indicating that refactoring makes economic sense in the long run by lowering the cost of adding new features.

holtkam2today at 6:03 PM

Great piece, but it misses the elephant in the room: the lion's share of economic benefit from refactoring will come from the fact that it makes it easier for humans to understand. That means 3am pages get resolved faster, fewer bugs will end up in prod, and your team can ship faster than your competition - gaining a leg up in the market. Most importantly, folks will be more comfortable accepting responsibility and ownership of a system when they understand it... this means that if/when something goes wrong, people will more quickly jump in and fix it, and when things could be better, folks will jump in and improve it.

pragmatictoday at 5:05 PM

Agent code can only be read and understood by agents. We’ve reached the point where people just can’t comprehend these giant code blobs.

Feature, bug or emergent property?

I don’t think the distinction matters as much as the reality.

We’re being locked into using the AI tooling bc the code was generated with AI tooling.

These giant files of doom were being generated by humans anyway and were very hard to work with. With LLMs it’s at last manageable or feasible to edit, refactor etc.

I honestly think LLMs are going to save us from ourselves as the codebases became too large and “messy” for humans to comprehend. (Mono repos of doom)

On a personal level these giant files are abhorrent but that’s just personal taste and I don’t think any of the Martin Fowler refactor/cleanup stuff is going to matter at all anymore. Kinda sad on some level.

show 4 replies
sltrtoday at 3:55 PM

the punchline: "Refactoring reduces token consumption"

I appreciate the effort to quantify the benefit rather than pontificate. It's worth mentioning Martin Fowler wrote a whole book on refactoring [1], in which he states, "to refactor, the essential precondition is [...] solid tests", which I think is the real benefit here, AI or not. Good tests protect against regressions, whether human or robot. They also help encode the spec, which humans and robots can read.

[1] https://www.oreilly.com/library/view/refactoring-improving-t...

show 1 reply
jmartricantoday at 8:41 PM

I think the name of the game is going to be "how do we maximize output while keeping token counts low". For example, finding ways to replace AI workflows, even if minor ones, with scripts/code.

Anthropic told me that I have till August 19th to be get my act together becuase they are going to reduce my token count by 50%. lol. I have been abusing my Pro Max allowance and need to start being less wasteful.

Articles like this, can help us come up with ideas on how to do it.

jimbokuntoday at 6:52 PM

> Add a new ItemWatchStore public async trait to the Firestore layer, following existing patterns exactly. The trait must have three methods:

async fn watch_item(&self, item_id: &str, user_id: &str) -> Result<()> async fn unwatch_item(&self, item_id: &str, user_id: &str) -> Result<()> async fn watched_items_for_user(&self, user_id: &str) -> Result<Vec<String>>

This shows the limitations of vibe coding. It takes someone with a long history of software development to prompt for something like this.

Even though the model is writing 100% of the code, still needed someone with a lot of programming knowledge to write the prompt.

show 1 reply
danbructoday at 4:15 PM

Interesting that the amount of code remained essentially unchanged. In my experience it is not unusual that refactoring messy code cuts the number of lines in half.

show 4 replies
jmartricantoday at 8:36 PM

The author said that Claude was not good at refactoring. But the author was using Sonnet 5. I supect Opus 5 would have done a lot better at refactoring. It would have come up with a multstep approach, i suspect.

imoverclockedtoday at 3:53 PM

It’s interesting that cyclomatic complexity or cognitive complexity scales with token usage. A codebase that enforces upper bounds on one of these two also (potentially) helps AI agents stay efficient.

persedestoday at 7:20 PM

Was hoping for a process diagram on how refactoring removes bottlenecks during software developement and allows you to ship faster etc :)

Still a nice writeup and love how these meta analysises (presumeably) done via AI can now easily capture metrics that inform your workflow.

t2ancetoday at 4:46 PM

Can't agree more. Feels like LLMs are not able to understand your requirements at a high level and always add complexity by default. Really need a handbook to guide them to do those cleanups. Obviously they know the knowledge in their weights but they just don't know how to apply it.

vehemenztoday at 4:25 PM

Opus/Fable 5 (or really, any thinking model) do a better job of refactoring than Sonnet would. I think the takeaways are still valid, just not as valid when using a more expensive model at a higher effort level.

vayliantoday at 3:55 PM

Interesting take-away:

> Claude is unable to look at code, look at refactorings in general and work out which are suitable to apply: a human needs to actively guide it.

Claude is happy to produce a very large Rust file. But you need human guidance to make it smaller.

show 1 reply
ChulioZtoday at 6:45 PM

I can very much relate to the experiences described in the article. In my projects, I have multiple Claude skills and rules aiming at making my files (the code, but also the Claude files themselves) more token-effective. I have seen huge differences in token usage before and after invoking those skills, which I regularly do as part of having Claude audit my projects; although I haven't measured them. Those projects are (like the one in the article) fully developed by Claude Code, so I found such audits and mindful token usage very necessary.

janpeukertoday at 6:46 PM

> Claude is unable to look at code, look at refactorings in general and work out which are suitable to apply

I am just sitting here waiting for Grady Booch to write "Architecture!"

awsglkhjtoday at 7:50 PM

I wonder, how close can we get to a reasonable simulator for testing software engineering practices before inflicting them onto the real world?

theturtletalkstoday at 4:17 PM

Make it work, make it right, make it fast, in that order

Make it right is the refactoring

kattenelvistoday at 4:44 PM

You can tell this is BS because there's no way that app is actually functioning at all. Fully vibe-coded, all that? No, I don't believe it.

defrimtoday at 3:49 PM

Being a bit cheeky here -- the amount of comments on this post is a telltale sign of how common / desirable refactoring is for the majority of developers (xD). It isn't our fault though, maybe if those pesky managers read this article then they would understand..

show 1 reply
gowldtoday at 6:20 PM

> Claude.ai was better than Claude Code

Why is this something users have to distinguish? Why can't these generative AIs choose good names for things?

paxystoday at 4:16 PM

I have been enforcing this myself through AGENTS files and other explicit instructions. What’s crazy is that none of the existing coding harnesses include such instructions by default. Two lines in Claude Code and Codex and the entire world would be writing better, more efficient code. Makes me believe in the conspiracy that these companies want more verbose code and longer files because it directly results in higher token usage.

show 1 reply
knighthackertoday at 5:19 PM

[flagged]

Natalia724today at 5:02 PM

[flagged]