Here are some techniques to help develop your programs.
Some of the more useful XP techniques.
cerr
or cout
to print intermediate results so that you can
see what the program is doing. So you can turn this on and off, create
a debug switch so you don't have to remove the cerr's later. Print a
prefix at the beginning of each message (eg, the function name) so that you know where it came from.
For example,
if (debug) cerr << "setName: name='" << name << "'" << endl;
at()
instead of subscription when accessing elements
in a vector. at()
checks that the subscript
is in a legal range. For example
sum = sum + weight.at(i); // Checks subscript range.Instead of
sum = sum + weight[i]; // No subscript range checking.
assert
to verify that things are as you think they are.
This is very useful in functions that use pointers
and expect a non-null pointer. Include <cassert>. For example,
assert(mylist!=NULL);
There are approaches to development such as Design by Contract (also called Contract-Driven Development) which emphasize writing pre- and post-conditions. Assert is one of the ways to implement this.