Refactoring your JavaScript Code — Part 3— Actually Refactoring
Refactoring code can be both liberating and indescribably frustrating as you tear apart working code to split it up into more user friendly bite sized pieces. I was looking back at an old project when I first started to code and realized that one of my functions was 108 lines. Yikes. If that isn’t a red flag alert, I don’t know what it.
When starting that method, I had the best of intentions, and checked every conditional in the book to ensure the proper data would get rendered. This however can cause for a long headache and monster sized function.
When thinking about writing clean code, you want to ideally have functions with a single purpose. Once you start adding in additional functionality, it’s probably time to create a new function.
Here are a few small examples of how I broke up my original createBook()
function into smaller parts. From here, you can start on your own journey and make refactoring your own.
In the above example, after refactoring, instead of just declaring the author variable, I initialized it with a default value. Then I simplified my conditional if/else to a simple ternary operation and added in comments.
In the above before code, that if
conditional continues all the way down to line 71. Lines 27–71 were taken out and refactored. Those lines were further broken down into two separate functions: check if the book exists in the database and check if the book has been suggested by the group already.
Refactoring can be daunting, but your future self and other programmers will thank you once your new code is more compact and readable! I hope this has helped and I wish you luck on your refactoring journey!