Friday, March 6, 2009

A Twisted Code Snippet.

The application is able to save images for an ID. When the changes are being saved, the comma-separated list of file names has to be inserted into the XML file. Easy. This small snippet have been sitting in the production code for about two years, until someone had to attach more than 2 images to a single ID.

(Easy to see that the logic works for one or two files, forming a string of '1.jpg,2.jpg'. If more files are to be saved, the string will look like 1.jpg,2.jpg3.jpg4.jpg' and all images except the first one will be lost).

id += "";

bool firstImage = true;
foreach (IDImage image in idType.IDImages)
{
id += image.ImageFilename;
if (firstImage)
{
firstImage = false;
id += ",";
}
}
id += "
";

I like bugs that are easy to fix and it looks like magic to a unsuspecting observer that a bug is fixed in a with a few keystrokes. How did the original developer come up with the idea, though, and why did it pass testing ...

id += "";

foreach (IDImage image in idType.IDImages)
{
id += image.ImageFilename;

//if not last image, add ','
if (idType.IDImages.IndexOf(image) < idType.IDImages.Count - 1)
{
id += ",";
}
}
id += "
";
by . Also posted on my website

No comments: