Dean said:
I am part way through developing a C++ application. I am developing it on my
own and using VC++ 6.0.
I am now at the stage where I wish to start tidying up my code.
Hmm. A rather common metaphor will help here:
Refactoring is like cleaning the kitchen after each meal.
If you put it off, the first few meals take less time. However, the next few
take incrementally more time. Eventually, you must waste time with extra
tasks, such as evicting insect colonies from your kitchen. Very soon, the
cumulative cost of the meals exceeds the cost of simply making dinner and
cleaning up each day.
So, that is "refactoring" - minor tweaks to the code you just wrote, while
it's fresh in your mind, and before it gets much chance to grow buggy.
I have lots of superfluous code that is hard to be sure about removing.
Then you need unit tests that cover each feature. You may delete any line
you like, and run the tests. If they fail, you Undo to restore the line, and
try again with a different line.
For example, I have classes that are ONLY used in methods that are never
called!
How did those classes get there?
Are there any tools that will help me get rid of this stuff?
Are any available free?
What about C++ refactoring tools in general?
There are very few automated refactoring tool projects for C++. Our language
is very easy to break. Such a tool must, for example, track down pointer and
reference aliases to a variable before moving it.
I would clean your codebase like this:
Get CppUnit, or one of its many clones (including NanoCppUnit).
Start a new project, in a new folder, and start with a single empty test
case. Make it pass. (This effort demonstrates you have installed CppUnit
correctly, and attached it to <F5> correctly.)
Now find the simplest, stoopidest, lowest-level method in your old project.
Write a test case that will fail if that method doesn't work. Run the test
and ensure it fails for the correct reason.
Now import the _minimum_ part of that method which makes that test pass.
Add test cases for each aspect of each feature that you need. Never add code
without first writing a failing test to prove you need it.
Refactor the code, a little, between making each test pass. Refactor in
small steps, to remove duplication, and pass all the tests between the
smallest number of edits possible. If they fail, hit Undo until they pass.
Eventually, you will be using the original program only as inspiration.
Tests will drive your development.
This technique is called "Extract Algorithm Refactor", and it will replace
your old project with a new one that surprisingly does not have any of the
cruft you witness. And you can probably do it in 1 day per 1,000 lines of
target code.