Keeping Your Code Clean & Dry
As a new programmer, one of the things I have struggled the most with is writing clean, concise code. The mark of a great programmer is being able to write code that works and does amazing things while simultaneously being succinct, easy to read, efficient, and clear.
We all know how easy it is to get carried away when we are in the zone, hoping to just make things work before the deadline. Before we know it, we have 450 lines of code and zero idea as to which chunk of code does what. While the code might work, it’s a mess and very difficult to maintain — if we can’t read what we wrote, how do we expect others to read and understand what we did? And if none of us can read the mess of code, how can we debug it when issues arise?
This is where refactoring comes in. According to Refactoring Guru (an awesome resource for learning more about refactoring code), refactoring is the “systematic process of improving code without creating new functionality that can transform a mess into clean code and simple design”. In other words, it’s the process in which we edit and improve our existing code in order to make it cleaner and more readable.
A good model to follow is the Red, Green, Refactor approach. In this approach, we can think of coding as three distinct phases. In the Red phase, we think about what we want to develop and write our tests. In the Green phase, we write code that makes our tests pass. In the Refactor phase, we refactor and improve our existing code.
A few tips:
- Add notes to your code where it is needed in order to keep things clear for yourself and others. But also be weary of adding too many comments — this makes code hard to read and clunky.
- Test your code often as you refactor. Make sure your code still works as you need it to after you’ve refactored.
- Keep your code DRY — if you find yourself repeating a line of code more than 3 times, it’s time to abstract some of your code.
- EXTRACT. Keep your code in small, easy-to-handle chunks. If any of your functions are too long and convoluted, extract some of the code to a new function and within the original code, invoke the new function.
- Keep your variable and function names as descriptive, simple, and consistent as possible. This will help you figure out what is doing what in your code.