# C++ Notes: Development Techniques

Here are some techniques to help develop your programs.

## Use Extreme Programming (XP) techniques

Some of the more useful XP techniques.

- Start very small. Get it running.
- On each iteration, add only a tiny bit of functionality. Compile. Test
- Tests should be written before the code! In fact there is a popular movement called Test-Driven Development (TDD) based on this idea.
- Have two people work on all code. Or at least review the code.
- Use Object-Oriented Programming (ie, classes) for all you code.

## Other useful techniques

- Use `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;

- Use `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.

- Use `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.

- Separate the user interface from the logic as much as possible. Put the code in separate files. The logic should have a header file that describes what it can do.
- Think in terms of classes -- grouping data and functions together that represent one element in your solution. When defining the classes, write the header file description first as a nice summary of what has to be done.
- Use standard library structures (eg, the STL classes) in preference to writing your own.
- Always write constructors for your structs/classes so that there are no unititialized fields.