unittest ddoc.

Gor Gyolchanyan gor.f.gyolchanyan at gmail.com
Mon Jan 30 08:39:50 PST 2012


I noticed, that a great way to document code is to put the contents of
its unittest in an example block of the respective ddoc:

/**
  * Transmogrifies an integer.
  * Params:
  *     integer = The integer, that will be transmogrified.
  * Returns:
  *     The transmogrified version of the integer.
  * Examples:
  * -----
  * assert(transmogrify(1) == 3);
  * assert(transmogrify(4) == 9);
  * assert(transmogrify(7) == 15);
  * -----
  */
int transmogrify(int integer)
{
    return integer * 2 + 1;
}
unittest
{
    assert(transmogrify(1) == 3);
    assert(transmogrify(4) == 9);
    assert(transmogrify(7) == 15);
}

The unittest is useful for both ensuring the expected behavior of the
code and to demonstrate it in a use case.
Wouldn't it be great if the compiler inserted the body of the unittest
ino the ddoc as an example? The condition to make that happen could be
the existence of ddoc comments on the code (at least empty) and the
unittest, in which case the text of the ddoc comment of the unittest
(if any) would be inserted right before the example.
This would automatically make any ddoc-commented and unittested code
documented with examples, which dramatically improve the learning
curve of the code being written.

-- 
Bye,
Gor Gyolchanyan.


More information about the Digitalmars-d mailing list