I\'ve been a professional software engineer for about a year now, having graduated with a CS degree. I\'ve known about assertions for a while in C++ and C, but had no idea t
All asserts should be code that could be optimised to:
Debug.Assert(true);
Because it's checking something that you have already assumed is true. E.g.:
public static void ConsumeEnumeration(this IEnumerable source)
{
if(source != null)
using(var en = source.GetEnumerator())
RunThroughEnumerator(en);
}
public static T GetFirstAndConsume(this IEnumerable source)
{
if(source == null)
throw new ArgumentNullException("source");
using(var en = source.GetEnumerator())
{
if(!en.MoveNext())
throw new InvalidOperationException("Empty sequence");
T ret = en.Current;
RunThroughEnumerator(en);
return ret;
}
}
private static void RunThroughEnumerator(IEnumerator en)
{
Debug.Assert(en != null);
while(en.MoveNext());
}
In the above, there are three different approaches to null parameters. The first accepts it as allowable (it just does nothing). The second throws an exception for the calling code to handle (or not, resulting in an error message). The third assumes it can't possibly happen, and asserts that it is so.
In the first case, there's no problem.
In the second case, there's a problem with the calling code - it shouldn't have called GetFirstAndConsume with null, so it gets an exception back.
In the third case, there's a problem with this code, because it should already have been checked that en != null before it was ever called, so that it isn't true is a bug. Or in other words, it should be code that could theoretically be optimised to Debug.Assert(true), sicne en != null should always be true!