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

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?

Print | posted @ Tuesday, May 01, 2007 1:12 AM

Comments on this entry:

Gravatar # re: What's Wrong With This Code? (#15)
by JohnB at 5/1/2007 3:26 AM

uhhh, it works on my computer? Please let me know why it shouldn't.
  
Gravatar # re: What's Wrong With This Code? (#15)
by scott at 5/1/2007 4:46 AM

John:

You should notice an extra character in the reverse string.

An unprintable character...
  
Gravatar # re: What's Wrong With This Code? (#15)
by Jason at 5/1/2007 12:00 PM

in VB, chars should be initialized like this:
chars = New Char(input.Length-1) {}

Notice the "-1". This is different than C#.
  
Gravatar # re: What's Wrong With This Code? (#15)
by JohnB at 5/1/2007 2:31 PM

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.
  
Gravatar # re: What's Wrong With This Code? (#15)
by scott at 5/1/2007 7:10 PM

John:

That's very odd. Let's exchange project files. My address is scott at OdeToCode.com
  
Gravatar # re: What's Wrong With This Code? (#15)
by James Curran at 5/2/2007 5:32 PM

>> 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.
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 1 and 8 and type the answer here: