I’ve been refactoring some code, and just have some thoughts on common things I’m fixing.
- Do the same thing at the same place. If the same snippet of code appears more than twice, e.g. checks if the user is logged in and redirects the user to the login page, it should be extracted. The fewer the control points, the easier it is to debug or change its implementation. IDEs will also allow you to easily trace who is using this functionality, which may help you access the risk of change. “More than twice” is a general guideline. You might see the potential of extraction even if the code only appears once or twice. Sometimes its not suitable for extraction even if it appears more than twice.
- Reduce condition nesting by quickly eliminating alternative flows. Leave the rest of the method for the happy/main flow. e.g. If you detect the user is not logged in, call the redirect and return. Using the return avoids needing an “else” after the if. Adding a comment here helps to understand the alternative condition (see point 5).
- Learn the lazy loading pattern. Helps reduce nesting as well if you understand how to apply ifs.
- Coherence and Coupling. Standard OOAD.
- Comments. Not easy to see good commented code. School only tell us to write comments. Who teaches how to write good comments at appropriate places? There’s no need to comment every line. Nor is it good to be comment-less.