DEV Community

salvat36
salvat36

Posted on

Refactoring Code for Improved Readability, Functionality and Efficiency

As a Software Engineer, we strive to write clean, legible, and easy to maintain code. In many cases the initial code is not necessarily this way, therefore we use the method of “Refactoring” to clean things up. A personal example of this can be found in the JavaScript snippet below.

Image description

Here we have a cluster of five separate functions to perform fetch() GET requests to various URL’S. Each function pulled a full season of tv episodes and passed them to the same repeated functions. Not only were these hard to read and maintain but also caused functionality issues as they were not always guaranteed to fire in chronological order. Knowing this wasn’t going to provide users with a positive experience, we searched for a better solution.

Low and behold, we came across JavaScripts “Promise.all” method which proved to be the perfect solution for this situation. As you can see in the refactored code below we were able to take five confusing/repetitive functions and condense them down into a few concise code blocks.

Image description

Let’s explain how; Promise.all takes an array as an argument (in this case allSeasons – an array of tv show “seasons”) and allows you to pass data down through your fetch calls as you would in a typical .then statement. The nifty part here is the response is not provided until all fetch calls are resolved (which solved our timing issues with the GET requests). Then using the .map() method, we create a new array converted into .JSON format. We are then able to use the forEach method to hand off the individual season's episodes to the spotlightEpisode, renderSeason, and HandleNavClick functions.

In conclusion refactoring and restructuring code is a major part of the software engineering journey and provides a way to produce clean, efficient code with an increased level of maintainability.

Top comments (0)