« Prediction Markets: A better way to predict project outcome | Main | Microsoft invented Ajax: Let's give credit where it's due »
December 28, 2005
"Safe" casting isn't safe, part 2
Many people wrote to me in response to my original post on this topic.
The common criticism was that I had excluded a third option when discussing downcasting: defensive programming.
For example, take the code from my original post and make it defensive:
object anObject = aHashtable[ USER_NAME ];
if ( anObject == null ) {
throw new ApplicationException( "expected user in hashtable, was null" );
}
if ( anObject.GetType() != typeof(User) ) {
throw new ApplicationException( "expected User instance in hashtable" );
}
User user = (User) anObject;
if ( user.isAuthenticated ) {
// ...
I don't like defensive programming, including pre and post-condition checking. The constant if-then-throw-exception logic obscures the intent of the code.
Compare the first example with this:
User user = (User) aHashtable[ USER_NAME ];
if ( user.isAuthenticated ) {
// ...
The second code snippet is straightfoward and clear. The first is relatively complex.
Use unit tests if you're concerned about the safety of the second example. If properly unit tested, you will have confidence that your non-defensive code works.
Posted by gsmith at December 28, 2005 05:17 PM