27 April 2007

Transforming Conditionals

Testing conditions is at least 50% of code in a typical program. When developer writes code, he not always knows in advance how method will look like at the end. Let's look at some typical cases.

This one is pretty simple method, which takes care of null object:

publicstring ConvertToString(object obj)

{

if (obj != null)

return obj.ToString();

returnnull;

}

Then I decided to add special handling for IConvertible:

publicstring ConvertToString(object obj)

{

if (obj != null)

{

IConvertible convertible = obj asIConvertible;

if (convertible != null)

returnConvert.ToString(convertible);

return obj.ToString();

}

returnnull;

}

Now it seems that it would have been better idea to check and return null immediately instead of placing all the code in the block. How can we fix this? I put caret on an "if" keyword and hit Alt-Enter.