Like many programming concepts, refactoring is broad concept and for different people it may have different meaning. I am sticking with definition of refactoring presented by Ken in his book. Refactoring can be defined as process of:
  • making code easier to understand
  • making code cheaper to modify
  • adding structure to code, if possible
At this point, I would also like to mention what refactoring is not. Refactoring is not optimization. I am sure many of us have been part of debates where engineers were hesitant to add structure to code arguing performance may deteriorate. In my experience, most of the times my own fears related to performance were baseless. Every application is different; however, key is not to speculate but to have performance tests, set the benchmark, refactor code and run performance tests again. Even if performance gets a hit, you might find it easier to optimize now that code is refactored and hopefully it will be easier to understand and cheaper to modify. Moreover, adding compute cycles will be far cheaper than adding extra development hours when making changes to poorly structured code.

When to Perform Refactoring:
Many of us may follow common advice of ‘don’t fix what’s not broken’ religiously. Software engineers have a profound liking to it. If you are working on code which can use refactoring, and you are certain that no enhancement requests will be coming in future, then it might make sense to leave code as it is. However, this rarely happens. Most of the times we are working on applications for which change requests are inevitable. For such applications, best time to refactor is when you are working on code adding new features or fixing existing bugs. This is the time to refactor, to change variable names, reduce parameter list, add structure to code, remove duplicate code and so on. Do not leave Refactoring to be performed as a separate activity at a different time. Obviously, test your changes using test cases while you are at it. If there is any part of code, which took you more than expected time to understand then this chunk of code might be good candidate for refactoring. Once you understand it, move your understanding from your head back to code by refactoring it. Your future self and other developers will thank you.

In the next post, I will be summarizing some of refactoring steps that I frequently use and which I keep in mind while doing code reviews.

This post is heavily inspired from book Refactoring: Improving Design of Existing code.


Popular posts from this blog

Practice Questions - AWS Solutions Architect - Associate Certification

AWS: Increase Connection Timeout

AWS Parameter Store