What is Opportunistic Refactoring!!
Looking at your existing code to add some more functionality. You found some miss placed class, or some unused variables, or might be something else. There comes the role of Opportunistic Refactoring also known as the boy scout rule. You use this opportunity to redo something or some part of your existing code. This way you can constantly and continuously modify and clean up your code. So that you are actually putting more value to the product for your client.
Who and When!!
Whenever you are planning to add some more lines to your existing code, look a while into your existing code before that. Look for any part of the code, that is irritating you. If you find any such block, then first work on it. Do whatever you feel like to make the things look good.
Now the question is who and when should perform the refactoring task in a software development lifecycle! There might be some scheduled refactoring phase available in some places, but the best option is to do it as an opportunistic activity.
That means, whenever some one spots a block of code, which is not as clearly written as it should be, takes this opportunity and rewrite the code to make it clear. As this approach makes the code better than it was found, it improves the health of the code base also. And if all the team members are doing this on a regular basis, they are also contributing in the process significantly.
The opportunity may come at any stage of implementing some new feature or at the time of fixing a bug. When you are trying to implement something new you may find that, it will be an easier process if the API of an existing class is structured differently. So you first make the necessary changes into the API, then start adding the functionality.
You may found yourself in such a situation, when you are actually in middle of another work, and an idea of another refactor strikes you. Don’t interrupt your current work. Rather make a note of the idea, finish the task on your hand then get back to the idea and complete it.
Things to keep in mind
In this process, you might then found that, some of the code you are writing is partially a copy of another block. Then you refactor that part to make things clean.
Do it in small units at a time. And run your unit test, every time you make any changes. If any thing goes wrong, go back to the previous state, find the problems and fix them.
This continuous attention to the code is very important, as it improves the quality of the product significantly.