CodeSOD: Joining the Rest of Us
Using built-in methods is good and normal, but it's certainly boring. When someone, for example, has a list of tags in an array, and calls string.Join(" ", tags), I don't really learn anything about the programmer as a person. There's no relationship or connection, no deeper understanding of them.
Which, let's be honest, is a good thing when it comes to delivering good software. But watching people reinvent built in methods is a fun way to see how their brain works. Fun for me, because I don't work with them, probably less fun for Mike, who inherited this C# code.
public List<string> Tags {get; set;} /// <summary> /// Helper function to convert a tag list to a space-delimited string representation /// </summary> /// <returns>the tags as a string separated by a space</returns> public string ToSpaceDelimitedString() { return ToDelimitedString(' '); } /// <summary> /// Helper function to convert a tag list to a delimited string representation /// </summary> /// <param name="delimiter">the delimiter to insert between the tags</param> /// <returns>the tags as a string separated by the specified delimiter</returns> private string ToDelimitedString(char delimiter) { StringBuilder delimitedTags = new StringBuilder(); foreach (string tag in Tags) { delimitedTags.AppendFormat("{0}{1}", delimitedTags.Length > 0 ? delimiter.ToString() : string.Empty, tag) ; } return delimitedTags.ToString(); }
It's important to note that ToDelimitedString is only called by ToSpaceDelimitedString, which starts us off with a lovely premature abstraction. But what I really love about this, the thing that makes me feel like I'm watching somebody's brain work, is their approach to making sure they don't have leading or training delimiters.
delimitedTags.AppendFormat("{0}{1}", delimitedTags.Length > 0 ? delimiter.ToString() : string.Empty, tag)
On the first run of the loop, delimitedTags is empty, so we append string.Empty, tag- so just tag. Every other iteration of the loop, we append the delimiter character. I've seen lots of versions of solving this problem, but I've never seen this specific approach. It's clever. It's not good, but it's clever.
And, as is good practice, it's got a unit test:
[Test] public void ToSpaceDelimitedString() { TagList list = new TagList(_blogKey); string expected = "tag1 tag2 tag3"; foreach (string tag in expected.Split(' ')) { list.Add(tag); } string actual = list.ToSpaceDelimitedString(); Assert.AreEqual(expected, actual, "ToSpaceDelimitedString failed"); }
What's interesting here is that they know about string.Split, but not string.Join. They're so close to understanding none of this code was needed, but still just a little too far away.
[Advertisement] ProGet's got you covered with security and access controls on your NuGet feeds. Learn more.