The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 717 other subscribers

C# Code fragments of the week

Posted by jpluimers on 2012/11/06

Boy, was I astonished to see the code fragments below in production apps. It is far more Daily WTF than Coding Horror.

However, it did make debugging the production problem at hand a lot worse than it should be.

First a few short pieces:

[sourcecode language=”csharp”]
private void method(Word.Application objNewDoc, string stringWithCsvSeparatedDotFileNames)
{
char c = char.Parse(",");
string[] wordAddIns = stringWithCsvSeparatedDotFileNames.ToString().Split(c);
}
[/sourcecode]

It took me almost a minute to understand what happened here. Especially because the names of parameters actually were pretty meaningless.

[sourcecode language=”csharp”]
foreach (string sFilename in attachments)
{
Word.Application mailDocument = new Word.Application();

string[] filePath = sFilename.Split(‘\\’);

string tempDirectory = GetTempDirectoryFromConfigFile();
object fileName = tempDirectory + filePath[filePath.Length – 1];

File.Copy(sFile, (string)fileName, true);
// some code that actually does something with the attachment
}
[/sourcecode]

It took me more than a few minutes to realize that:

  1. The tempDirectory needs to end with a backslash
  2. mailDocument (not a document, see below), will stay alive when File.Copy(…) throws an exception.

[sourcecode language=”csharp”]
internal virtual bool Method(/* parameters */, Word.Application objDoc)
{
// lots of pre-initialized empty string variables that are used at the very end of the method

Word.Application objNewDoc;
if (objDoc != null)
{
objNewDoc = objDoc;
}
else
{
objNewDoc = new Word.Application();
}

// lots of Object variables for COM, including:
Object missing = Missing.Value;
Object bFalse = false;

try
{
// lots of code that does not use objNewDoc
}
catch (IOException IOex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw IOex;
}
catch (Exception ex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw new Exception("Some error message.", ex);
}
finally
{
// empty finally block
}

try
{
// actual coder that does use objNewDoc
}
catch (Exception ex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw new Exception("Some error message.", ex);
}
return true;
}
[/sourcecode]

I rewrote the whole piece into separate methods.

Luckily the person who wrote this got promoted away from programming a few years ago.

–jeroen

Leave a Comment