/ akroncodeclub

The Akron Code Club, Meeting New People, and the Unsplice Kata

The Akron Code Club had an amazing turnout Monday night. Roughly 30 people.

I got to talk to Vince, who is just recently getting into C# and came out for his second time, Tasha who heads up the UX Akron user group, Stephanie who lives out of state and is currently attending the Software Craftsmanship Guild bootcamp in Akron… I always feel energized afterwards, getting to talk to people and find out where they’re at with things, which is saying something because I’m generally introverted and find talking to be draining. It’s just fun.. a bunch of people coming out for no reason other than to learn.

Being in a STEM field is great.

Heather led us in the Unsplice kata. If you’ve never tried a code kata before, they’re usually small/trivial exercises, and you’ll tend to want to jump ahead and solve it quickly. I find this especially tempting in C#, where I have the enormously powerful .NET framework at my fingertips.

But code katas are about the journey, not the destination. Completing the exercise in its entirety is secondary; it’s about spending an hour methodically moving forward, usually practicing test driven development (TDD) with another programmer (that’s the “pair” part). It gives us a chance to work with others, learn how they approach a problem, learn different languages and testing frameworks, and more.

No deadlines. No future maintenance. When you’re done, just delete it.

If you are familiar with katas, and are looking for some different ones, try out cyber-dojo.org. It currently has about 40, and a couple dozen languages to choose from (it’ll setup a small test environment for you to get started with the kata).

Anyway, back to Monday night. We paired up and practiced red-green-refactor. That means the first person writes an empty method (so that the project compiles), and a test for the first condition stated in the kata. It fails. Then the second person fixes the code just enough to make it pass, then writes her own test for the second condition, which will fail. Back to the first person. Back and forth, on and on…

pingpong

The Unsplice kata was a new one for me. Here’s the description:

Given a string, strip all occurrences of consecutively occurring backslash and newline characters.

For example, assuming that "\\" represents ‘\’ and “\n” represents ‘\n’:

  • “ab\\ncd\\nef” –> “abcdef” (two stripped out)
  • “abc\\ndef” –> “abcdef” (one stripped out)
  • “abc\n\def” –> unchanged (wrong order)
  • “abc\def” –> unchanged (no \n)
  • “abc\ndef” –> unchanged (no )
  • “abcdef” –> unchanged

Funnily enough, it took me and my pair about 3 minutes (most of which was setting up a project in Visual Studio and downloading nUnit from NuGet) to realize that using the built-in .NET function solves for all the above cases and… done.

public string CleanString(string input)
{
    return input.Replace("\\\n", "");
}

Someone nearby using Java used the similar string.replace() method, and turned to us looking just as confused. Someone else solved it in one line of regex, I think in php. I kinda felt like we cheated!

Realizing that using a built-in library in this case might not be in the spirit of the kata, we decided to reinvent the wheel. Not something I’d do IRL but necessary for the exercise!

don't reinvent the wheel

Here’s what we came up with. Actually, we came up with about 90% of this, couldn’t get all the tests to pass, and ultimately just watched some as others discussed how they’d gotten it to work in languages like Ruby and Go. Some didn’t have a library to use, and had to implement their own solution. Some did, and just went with it.

As usual for these kata nights, the languages used were all over the board (there’s typically see c#, ruby, javascript, erlang, vb.net, php, f#, etc), so that’s pretty cool. If you’re interested in a language, you could probably find someone at ACC who’s at least somewhat familiar with it.

I wrapped up our code after getting home later. Basically, it sets a flag if ‘\’ is encountered, then checks the state of the flag if ‘\n’ is encountered.

public string CleanString(string input)
{
    var chars = new List<char>();
 
    var wasLastCharBackslash = false;
 
    foreach (var c in input)
    {
        if (c == '\\')
        {
            // cover the possibility of two consecutive escaped backslashes
            if (wasLastCharBackslash)
                chars.Add('\\');
 
            wasLastCharBackslash = true;
            continue;
        }
 
        if (c != '\\' && c != '\n')
        {
            if (wasLastCharBackslash)
            {
                chars.Add('\\');
                wasLastCharBackslash = false;
            }
            chars.Add(c);
        }
        else if (c != '\n' && wasLastCharBackslash)
        {
            chars.Add('\\');
            wasLastCharBackslash = false;
            chars.Add(c);
        }
        else if (c == '\n' && !wasLastCharBackslash)
        {
            chars.Add(c);
        }
        else
        {
            wasLastCharBackslash = false;
        }
    }
 
    return new string(chars.ToArray());
}

Someone at the meetup suggested that we might be able to take advantage of the enumerator’s peek method to preview the next character (to see if it’s a ‘\n’ following a ‘\’), which I’ve never looked closely at. It turns out that, while java has that ability, c# does not (unless your Jon Skeet, then you write your own, on the fly). I don’t actually know what C#’s built-in Replace() method does, because it’s marked as “extern” and the source code isn’t readily available (I usually use ReSharper/dotPeek).

Here are our tests, written in nUnit. (The IDE and testing suite of your choice, if you have them available, are far easier to work in than the tiny coding-dojo window). We took advantage of the “TestCase” attribute to reduce the number of nearly-identical tests we would have had to write.

[TestFixture]
public class UnspliceTests
{
    private UnspliceKata kata;
 
    [SetUp]
    public void Setup()
    {
        kata = new UnspliceKata();
    }
 
    [Test]
    [TestCase("ab\\\ncd\\\nef", Description = "Two to strip out")]
    [TestCase("abc\\\ndef", Description = "One to strip out")]
    public void RemoveBackslashAndNewLine_WhenOccurringConsecutively(string input)
    {
        var result = kata.CleanString(input);
 
        Assert.AreEqual("abcdef", result);
    }
 
    [Test]
    [TestCase("abc\n\\def")]
    [TestCase("abc\\def")]
    [TestCase("abc\ndef")]
    [TestCase("abcdef")]
    public void DoNotRemoveBackslashAndNewLine_WhenWrongOrder_OrNotConsecutive(string input)
    {
        var result = kata.CleanString(input);
 
        Assert.AreEqual(input, result);
    }
}

The photos Don’t reinvent it and Nuke Everything and Start Over are licensed cc by-nc-sa 2.0.


Grant Winney

Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.

Read More