DEV Community

Alex Morton
Alex Morton

Posted on • Updated on

Rinse, Repeat, Refactor

Happy Monday! Yesterday, I sort of broke my 'no work on the weekends' rule and worked a bit on my JS course. Mostly just went over a coding challenge a couple of times to really cement in the information. It was great and I got a lot more practice with writing good, effective code.

One thing I do when I'm repeating a challenge or a project more than once is to make sure I really stop and think about the solution to something - especially when I'm stuck, but I know I've found a similar answer before.

It's extremely helpful to get yourself a working solution before checking the solution so that you can put the puzzle pieces in your head before glancing at something that will immediately remind you of the correct answer without the work of those neurons firing in your brain to retain the learning.

I'll put in a little example here. For the coding challenge, we had to generate a couple of reports about the three parks and four streets in a tiny town using classes and functions to display the reports to the console.

For one part of the challenge, we needed to log a statement to the console if any of the parks had over 1000 trees (the number of trees was included as a parameter in the Park class as numTrees). Here was my first attempt in thinking it through by myself:

const checkNumTrees = () => {
for (const element of parks) {
if (element.numTrees > 1000) {
console.log(${element.name} has more than 1000 trees with ${element.numTrees} trees in total.);
}
}
};

So, the above function gets the job done, albeit not very beautifully. Going through it the next time, here's how it could be simplified:

parks.forEach(element => {
if (element.numTrees > 1000) {
console.log(${element.name} has more than 1000 trees with ${element.numTrees} trees in total.);
}
});

So now it's been simplified by using the calling the forEach method on the parks array while still using the if statement within the function. Better, but here's where it could be improved even further:

const index = p.map(el => el.numTrees).findIndex(el => el >= 1000);

console.log(${p[index].name} has over 1000 trees with a total of ${p[index].numTrees} trees.);

I'd say that overall, this last refactor gets the job done very cleverly, but for me, the clearest way of writing it would be the second way. I see it, and I immediately know what the function does and what results it should return; whereas, with this last refactor, it would definitely take me a minute to figure it all out.

I wonder if that'll change as I get more and more experience (probably). Although I've often heard that it's better to write clear, easy code than it is to write overly clever code.

This post was originally published on April 6, 2020 on my blog.

Top comments (0)