First write a regression test suite.
You need protection from introducing new bugs as you refactor your code.
Some general tips:
- Ensure each module can be easily tested in isolation.
- Interfaces matter. Minimize the exposure of implementation details; provide stable interfaces to protect the remainder of the program from the details of the implementation (which are likely to change) - don't just provide full access to the data used in the implementation. (See Information hiding).
See also: