There is a saying, “writing is rewriting”. Each time I look at my code several years earlier, I always feel headache and would like to rewrite them, or improve them with what have been learnt so far, so that they are easier to read, to understand and to update.
In general, code refactoring refers to the process of changing bad codes into cleaner, purposeful, human-readable, reusable code in order to be cost effective, easy to maintain and collaborate, and probably a better performance.
Some signs that the code can be refactored
- Inline comments: Every time there is an inline comment, that means the code is difficult to understand and therefore there is a need to rewrite it so that it becomes meaningful even without the inline comments.
- Repeated code: Duplicating codes make it difficult to maintain. If there are changes, you have to go and make changes in all the places.
- Fat functions: Functions that do too many tasks are difficult to maintain.
- Big decision trees: if or switch with too many different possible branches or too many tasks inside.
What can be done to improve these situations?
- Naming conventions: names of the functions, variables, classes, interfaces, and namespaces should explain itself. It should tell us what it does or what it represents. This eliminates the need to use inline comments.
- Returns early in a function, so that the function does not need to get to the last line to stop. If there is a condition that it can stop earlier, just return.
- Break up into small functions, with each function to be approx. 15 lines of codes and do only one task.
- Avoid the use of Globals because they are writable which make the code prone to bugs and may produce unexpected behavior. Instead, write an API to fetch the data.
- Avoid the use of many level nested conditions. Instead, break them up into small functions and returns early. This will also help you to get rid of repeated code.
- Avoid unnecessary codes, and make it as fewer lines as possible.
Above all, we should think about the intent of the code, and try to make it less complexity with fewer lines. Easy for us, easy for people who will be after our work.
That’s what I have learnt today by reading the book on KnowTheCode. Although it sounds so clear, it will for sure require a lot of practices everyday to deeply understand and let it be a good habit. I recommend that you also come to the website and grab yourself one PDF of the book. It is only more than 100 pages but practically provides a lot of code examples.