To demonstrate this I am going to take a very simple function from MSDN on the C# ++ operator . Here is the extract of MS' example:
The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:
RemarksThe first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
Numeric and enumeration types have predefined increment operators. User-defined types can overload the ++ operator. Operations on integral types are generally allowed on enumeration.ExampleOutput
// cs_operator_increment.cs
using System;
class MainClass
{
static void Main()
{
double x;
x = 1.5;
Console.WriteLine(++x);
x = 1.5;
Console.WriteLine(x++);
Console.WriteLine(x);
}
}
2.5
1.5
2.5
Although we are accustomed to these types of examples have a think about how hard you have to work to undertand it. The example on it's own gives no indication of what behaviour it is demonstrating (which is explained in complex english in the preceding text) and the call and the result are nowhere near each other - how often do my eyes have to refocus (look at the first Console.Writeline, then the first line of the output, then the explanation, match them up, look at the second Console.Wr... phew)? And this is just a simple example with a few behaviours.
Here is the same thing using tests (I've tried to closely match MS' own text for test names):
using NUnit.Framework;
[TestFixture]
public class IncrementOperatorBehaviour
{
[Test]
public void IncrementAsPostfixIncrementsValueByOne
{
double x = 1.5;
x++;
Assert.AreEqual(2.5, x);
}
[Test]
public void IncrementAsPrefixIncrementsValueByOne
{
double x = 1.5;
++x;
Assert.AreEqual(2.5, x);
}
[Test]
public void IncrementAsPrefixGivesResultAfterIncrement
{
double x = 1.5;
Assert.AreEqual(2.5, ++x);
}
[Test]
public void IncrementAsPostfixGivesResultBeforeIncrement
{
double x = 1.5;
Assert.AreEqual(1.5, x++);
}
}
How much clearer is that? You even have the satisfaction of seeing it all go green when you run them!