DEV Community

Cover image for The Art of Refactoring
Alex Hyett
Alex Hyett

Posted on • Originally published at alexhyett.com on

The Art of Refactoring

Unfortunately not all the code we write is perfect first time, or after several attempts in most cases. Taking a piece of code and refactoring it into something better takes skill and only really comes with experience and hindsight.

This week I was implementing an endpoint that makes some calculations over a period of data, and then shows the aggregated result. I was quite pleased with the implementation and the code was quite concise.

The next part of the feature was to then implement a graph showing the calculated data per day over that period.

It was then that I realised my mistake.

Producing the data for the graph involved making the same calculations but on daily data. Yes I could reuse the same methods from the previous task, but this still involved making another database call and recalculating everything.

It would have been more efficient to start with the daily data, make the calculations and then just aggregate the result for the final stats.

It took me a couple of hours to refactor the code but when I finished and all my tests were still passing, I was pleased that I took the time. Now I had just one database call and the calculations only needed to be done once over the data.

This kind of refactoring not only made the code easier to read, but it also reduced the amount of code I needed and had significant performance improvements as well.

When to refactor #

Refactoring code is an art. It is similar to drawing or painting a picture. You start with a rough drawing which you then improve by adding detail.

Once your picture is mostly done you take a step back and see which areas you can improve. It is here where you need to be careful not to overdo it and ruin the picture.

You have to know when to stop, and often what you leave out is more important than what is added.

The same is true for refactoring code. As developers, it is easy to keep refactoring code to improve it, but to what end?

One of the arguments for refactoring code is to make it more maintainable and easier to extend. So you put in the additional effort after writing your code so it is the best it can be, The Sistine Chapel of functions.

But what if that code never needs to be extended or never needs to be touched again? Was the extra time spent refactoring worth it?

In most cases your original version would have been fine, easy enough to read and most importantly, it works.

I remember as a junior developer refactoring a class so that many of the methods could be reused. I made a few improvements and then kept going. Overall I managed to halve the amount of code in the class, but as a result introduced generics and tuples that just made the code complicated and harder to maintain.

If your code is truly awful, by all means spend a bit of time to make it better.

Chances are however, it is good enough. If the code is difficult to extend then you will find that out when you come to extend it. If you don't end up extending it then you saved yourself a lot of time.

All code has a “Best before date” #

As developers, we think that our code needs to be perfect as it is going to last forever, but in reality every bit of code has a shelf life.

Yes, if you are adding code to the Linux kernel it will likely last decades and the same is true for other industries.

For most of us however, your code may only have a shelf life of 5 years or so. I have worked for fast-growing companies where teams were replacing “legacy code” that was only written 2 years ago and others where the company didn't even last that long.

The code and infrastructure you write for an application that only gets 1 request a second is going to be very different to one that gets 1000 requests a second.

You might say you should have started with the end result, but that is hindsight at play again. If you started with the final version and the application never went above 1 request a second, you would be blamed for over engineering.

There are definitely benefits with refactoring, but you have to pick the right time to do it.


❤️ Picks of the Week #

📝 ArticleSony, Ubisoft scandals lead to California ban on deceptive digital goods sales — This is a step in the right direction. I have mentioned before that for most digital goods you are not buying it but merely renting it. The same is true for all the games I have bought on Steam. They might get pulled from the store or the backend servers shutdown rendering the game unplayable.

📝 ArticleThe different energy footprints of different programming languages — The stats shown here are unfortunately 7 years old, and I know at least C# has made many performance improvements since then. It would be interesting to see what the results for these would be now.

📝 ArticleFraud, so much fraud — I remember when applying trend lines to my experimental results at university, that my conclusion would have been more convincing if only I could leave few outliers out. In my case I was merely trying to replicate already proven results, however I am not surprised that this sort of fraud can go unnoticed for so long in the academia.

💥 ComicAmusing Ourselves to Death (2014) — I enjoyed 1984, but I still need to read Brave New World. Looking at this comic it does seem we are getting closer to Huxley's version of the future than Orwell.

📝 ArticleSome Go web dev notes — I have been meaning to try Go. If you are using Go or plan to these notes might be useful for you.

🗺️ MapMap with public fruit trees — Sadly this map is a bit sparse for the UK, but I like the idea. It would be good if there were more fruit trees that people could just pick from. Unfortunately we live in a world where greedy people would likely take advantage.

📝 ArticleRust needs a web framework for lazy developers — Like Go I have been meaning to learn Rust. If I have to implement even basic things myself though I will likely give it a miss. Half the reason I always come back to C# or JavaScript is because I know what libraries I can use to get the job done.

😄 Fun ToolBop Spotter — This is genius. I really like things like this. It is a creative use for tech and reminds me I need to make more fun things like this.

📝 ArticleWhere I'm at with note taking apps — I use Obsidian for writing this newsletter and my other notes. Obsidian is a power tool, but it can be a bit much just for writing. iA Writer looks good, and I might have to give it a try.

📝 ArticleTerminal colours are tricky — The dark blue writing on black really bugs me and this article finally prompted me to update it. If you want to go down a terminal colour rabbit hole then give this a read.

📝 ArticleDon't build your castle in other people's kingdoms (2021) — Still relevant today as it was 3 years ago. This is why I write this newsletter on my own domain instead of Substack.

📝 ArticleHow to share your access to media with family and simultaneously sweep the annual nerdy nephew of the year awards — I use Tailscale myself for accessing all my home services. I didn't know it worked on Apple TV too. This is a good way to get around companies coming down on credential sharing.

📝 ArticleEverything I Learned From Iron Maiden About Life — I haven't listened to Iron Maiden for years, but I really should. There is some great advice in this article.


💬 Quote of the Week #

One of the biggest concerns people have when they talk to me about quitting their job is how to make money. That is certainly important, but a more interesting path is possible if you start with what brought you alive in the past. Injecting the energy from these pursuits can lead you in a different direction and can help you figure out what to work on while taking the first steps toward creating a life you truly enjoy.

From The Pathless Path by Paul Millerd.

Top comments (0)