[snip]
I would work on making that function's unit test self-documenting before
working on its comments. You can't test a comment.
Firstly, how can you write a unit test if you don't specify the
semantics of the function? Secondly, how do you expect clients of your
software to understand how it works? By reading source code? No. They
will look at the header file, since that, and the library, is all they
have.
So, in fact, you *only* test comments! For example,
bool operator<(const IPv4Address& lhs, const IPv4Address& rhs);
What does this function do?
1. Behavior
// Return true if the 'lhs' object is less than the 'rhs'
object,
// and false otherwise.
Okay, how do you construct a unit test around this behavioral
description? What values should you choose? What should the unit test
look like?
2. Definition of Terms
// 'lhs' is less than 'rhs' if its address is less than that
// of 'rhs', or if its address is equal to that of 'rhs' and
// its port number is less than that of 'rhs'.
This is a lot clearer. Now we can at least choose test values and know
what result to expect. But why should 'IPv4Address' objects be ordered
in this way? It's rather arbitrary. We could just as easily have
ordered them by port number. In fact, some clients might prefer such
an ordering if they want to group "connections" by their service
endpoint (i.e., group 'IPv4Address' objects representing connections
to various machines by port number). Well, your clients have a right
to know your motivations.
3. Note That
// Note that this arbitrary ordering of 'IPv4Address' objects
// is chosen primariliy to facilitate interoperability with
// STL Sorted Associative Containers.
Now that you've sufficiently *documented* the semantics of your
function, and your motivations, you can test your function:
Unit Test (in a separate .cpp file with a 'main')
// TESTING LESS THAN (<) OPERATOR
//
// Concerns:
// Subtle differences in IP address and port number of two
'IPv4Address'
// objects are detected by comparison with the less-than
operator.
//
// Plan:
// Specify a set S of 'IPv4Address' objects each having
variations in
// the IP address and/or port number. Compare each pair (u, v)
in the
// cross product S x S, such that u != v.
//
// Create a 'std::vector', 'W', of 'IPv4Address' objects that
acts as a
// control. Create a copy of 'W' named 'X'. Randomly permute
'X', and
// verify that 'X' is different than 'W'. Sort 'X' using
'std::sort',
// implicitly exercising the defined less-than operator, and
verify that
// 'X' is the same as 'W'.
//
// Testing:
// bool operator<(const IPv4Address& lhs, const IPv4Address&
rhs);
Okay. Now you know exactly the semantics of the function and the
structure of the unit test. You also know that your motivations are
validated by a concrete example. I have not written *any* code. The
function and the test case are *documented*, not "self documenting."
/david