On : Downcasting is a Code Smell

I almost always tend to agree with Jeremy D. Miller over at CodeBetter.Com. This time, I still agree with him. I agree so much that I am wondering if he is joking or was having a bad day and posted this in frustration.

Jeremy, of course Downcasting is a code smell. It does all the bad things that you said it does. I thought that this was a given. I see code like this and I immediately assume that the person who wrote it either 1. was in too much of a hurry to take pride in their work, or 2. had no idea how to program using good OO concepts.

When I run into code like this I usually get VERY frustrated. It is never fun to run into ugly code. It is more frustrating to run into code that could be so much better with just slightly more than trivial understanding of the underlying libraries. I guess this is exactly what I wrote on with respect to System.Data over a year ago. Not the downcasting part, but rather just good use of the supplied interfaces instead of always using the concrete class.

It was downcasting that inspired me to write those posts over a year ago. I was working with a project which was using the DAAB from EntLib 1.0. DAAB returns IDbConnection and it was being Downcast to SqlConnection everywhere it was using in this project. I cursed a bit. Then I realized that all of the code was in my hands, and I went about cleaning it up. It was not difficult. That was something I COULD take pride in. Stupid, yes. Maybe a waste of time, but now I know that the next time I go into that module I won’t be disgusted by what I see.