A quick mini rant as I work on some code tonight. Disclaimer: I am far from perfect but I strive to improve at all times.
If you are developing a class library that you make freely available on the internet, you should realize that someone might actually download and use it. In light of this, error handling is important. I am using an FTP library for the compact framework that I downloaded from a reputable site.. My clients were having FTP issues this past week though, and I had to duplicate a situation that did not come up in my testing. For reasons I won't get into, their servers have issues sometimes, so I had to implement a Re-try mechanism for the FTP items in question. I tracked the issue down to this code:
FileStream fs = new FileStream(localFileName,FileMode.Open);SendStream(fs, remoteFileName, type);fs.Close();
See any issues here? Maybe if I compare it to what I changed it to?
FileStream fs = null; try { fs = new FileStream(localFileName,FileMode.Open); SendStream(fs, remoteFileName, type); } finally { if (null != fs) { fs.Close(); } }
Sometimes things will blow up. In this example, if the FTP send fails, which is entirely likely due to network connectivity issues then the file stream will not be closed and cannot be closed because I've lost my reference to it. The Re-try was then pointless since the file is locked by an object off in la-la land that has not been garbage collected yet. While I'm at it, I don't know how many obscure bugs I have traced back to a resource such as a SqlConnection or DataReader not being taken care of in a Finally or Using block.
There, I feel better. The author has still saved me a ton of time with a very easy to use library. The next step is for me to be a good citizen and politely inform them of the issue. Better code for all. I would certainly want someone to inform me if I had released a library with bugs. Happy coding.