Refactoring

I’ve been refactoring some code, and just have some thoughts on common things I’m fixing.

  1. 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.
  2. 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).
  3. Learn the lazy loading pattern. Helps reduce nesting as well if you understand how to apply ifs.
  4. Coherence and Coupling. Standard OOAD.
  5. 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.

Leave a Reply