What's Wrong With This Code? (#15)

Tuesday, May 1, 2007

Mortimer is taking up TDD, and starts a new project by writing the following test.

<TestMethod()> _
Public Sub CanReverseString()

    Dim input As String = "OdeToCode"
    Dim result As String = Utility.ReverseString(input)
    Assert.AreEqual("edoCoTedO", result)

End Sub

Yes, it's another one of those big projects that reverses strings all the time.

With a test in place, Mortimer writes the following stub.

Public Class Utility
    Public Shared Function ReverseString( _
        ByVal input As String) As String
 
        Return Nothing

    End Function
End Class

Good news - the test fails! Now it's time to provide a real implementation...

Public Class Utility
    Public Shared Function ReverseString( _
        ByVal input As String) As String

        Dim chars As Char()
        chars = New Char(input.Length) {}

        For i As Integer = 0 To input.Length - 1
            chars(i) = input(input.Length - i - 1)
        Next

        Return New String(chars)

    End Function
End Class

Mortimer thinks he has everything straight - but the test still fails! What could be wrong with Mortimer's ReverseString?


Comments
JohnB Tuesday, May 1, 2007
uhhh, it works on my computer? Please let me know why it shouldn't.
scott Tuesday, May 1, 2007
John:

You should notice an extra character in the reverse string.

An unprintable character...
Jason Tuesday, May 1, 2007
in VB, chars should be initialized like this:
chars = New Char(input.Length-1) {}

Notice the "-1". This is different than C#.
JohnB Tuesday, May 1, 2007
Ok, I agree that the init of the array includes an extra element but I wired this up with NUnit as well and the test passes. I do not get any unprintable characters.
scott Tuesday, May 1, 2007
John:

That's very odd. Let's exchange project files. My address is scott at OdeToCode.com
James Curran Wednesday, May 2, 2007
>> I do not get any unprintable characters.

If that random character happens to be a zero (which in theory should happen no less than 1 in 256 trials, but in practice probably occurs much more often), you will accidentally get a correct string.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!