OdeToCode IC Logo

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?