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”?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: