How to refactor some horrible code

David Torres
Feb 10 · 5 min read
Pyramids in the desert
Pyramids in the desert
Pyramids are beautiful, if-else pyramids are not. Photo by Steffen Gundermann on Unsplash
I didn’t actually had to… but look at it, I “had to” (╯°□°)╯︵ ┻━┻

1. Give that code 100% test coverage

I was not tasked with refactoring this code, I made that call. But I didn’t know how much time it was going to take (time I should be using to deliver something else).

The primary benefit of TDD is the ability to refactor without fear, and without cost — Robert C. Martin (Uncle Bob)

What is this thing I’m feeling? Oh yes, it’s my confidence raising!

2. Extract functionality

Now that we have more confidence thanks to our tests, we can start breaking the code apart. Let’s start from the beginning. We see that protocol is assigned different values depending on the service, environment, client/server side… and then added to the rest of the url at the end of the function.

const url = `${protocol}://${domain}`

3. Simplify

Apart from the separation of concerns, the advantage of extracting the different parts of the url into different functions is that the conditionals can be simplified further. Before, some parts of the URL were limiting the simplification as they required multiple conditions to be met. Now, they are separated so we don’t have to worry about that.


Thanks to the extraction of functionality we ended up with an endpoint() function which is a pleasure to write.

It is so simple that it should be a crime
Image for post
Image for post
GitHub comment in the PR
Image for post
Image for post
A team mate making my day

Gousto Engineering & Data Science

Gousto Engineering Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store