Article 6DESV CodeSOD: Taking up Spaces

CodeSOD: Taking up Spaces

by
Remy Porter
from The Daily WTF on (#6DESV)

Anderson sends us a bit of C# code that does the simple job of removing multiple spaces, i.e. it converts "AB" to "AB". And, much to my surprise, I learned something about C# from reading this code.

private string RemoveDoubleSpaces(string strName){ string newStrname = null; for (int i = 0; i < strName.Length; i++) { if (i > 0) { if ((strName[i] == Char.Parse(" ")) && (strName[i] == strName[i - 1])) { continue; } else { newStrname += strName[i].ToString(); } } else { newStrname += strName[i].ToString(); } } return newStrname;}

There are some "interesting" choices here. Like using Char.Parse to convert the string " " into the character ' ', when they could have just used the character in the first place. Or the special case first step of the loop- a conditional that gets checked for every iteration when we know that it only executes the first time. We could easily move the initialization of newStrname outside of the loop and then just start the loop at 1, greatly simplifying the code.

But speaking of newStrname, this is where I learned something. At first glance, I assumed this code would just crash if it ever actually ran- newStrname is initialized to null, and then we call += on it- surely that doesn't work on a null value? But it does.

And in retrospect, it makes sense: null + "some string" also works, and just does the sane behavior of returning "some string". In fact, the behavior is so obvious, that I now feel silly for thinking this worked any other way. Still, I was surprised that this code worked.

Speaking of code that works, Anderson threw all of this away and replaced it with the simpler return Regex.Replace(strName, @"\s+", " ");, which isn't doing exactly the same thing as the original code, but actually maps better to the requirement (the rule was that all whitespace should be replaced with a single space, not just space characters), so the code is simpler and a bug got fixed.

buildmaster-icon.png [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments