Misunderstanding of Defensive Coding – Timere Erroris Syndrome

While going through the codebase of the counterparty risk reporting system I came across thousands of cases where you can sense that the developer is afraid to write code that throws an exception.

The most primitive examples is returning true/false if the operation completed successfully, but this one is very easy to spot and therefore fix. The same applies to handling all exceptions.

But the one which doesn’t stand out very often is the usage of ‘as’ instead of plain casting or combination of ‘as’ and then a null check. Without a null check there is a possibility of spotting a bug at the early stages of testing, even though instead of ‘InvalidCastException’ you get a ‘NullReferenceException’. But with a null check in place the bug would go pretty much unnoticed. The question should then be – why a certain parameter, item in the array, should not be of the particular type? If there is a valid reason or are you just “scared”?

Why put code inside finally statement with empty try statement

When browsing .NET source code you might come across an empty try clause and some code in the finally clause:

try
{
}
finally
{
// few lines of code here
}

The answer is to guarantee the execution of the code in case something calls Abort() on the thread. Since .NET 2.0 execution of the code in the finally statement is guaranteed even if something calls Abort() on the thread. In the earlier versions of.NET it was possible that the finally clause is never executed. I don’t expect to ever write anything that would leverage this, however it still nice to know.

Blog at WordPress.com.

Up ↑