When you find you have to add a feature to a program, and the program's code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.
Before you start refactoring, check that you have a solid suite of tests. These tests must be self-checking.
Refactoring changes the programs in small steps. If you make a mistake, it is easy to find the bug.