My first "refactoring"
Do you think the code looks a little ugly?
Public Function i2r(i As Integer) As String
If i = 1 Then
i2r = "I"
ElseIf i = 2 Then
i2r = "II"
ElseIf i = 3 Then
i2r = "III"
ElseIf i = 4 Then
i2r = "IV"
ElseIf i = 5 Then
i2r = "V"
ElseIf i = 6 Then
i2r = "VI"
ElseIf i = 7 Then
i2r = "VII"
ElseIf i = 8 Then
i2r = "VIII"
End If
End Function
I see a pattern with the 1, 2 and 3 and 6, 7, 8. I wonder if I can do something with the repeating “I”s.
But what to do?
When I consider the code, I see that there are two ways in which I think I can tidy up the code (refactor). First, I could turn 1, 2 and 3 into a loop. Second, I could turn 6, 7 and 8 into (5 + 1, 2 or 3). I think I’m clever enough to do both at the same time but then I recall the XP idea of doing things one at a time, since it’s more likely to work/ less likely to break. I flip an imaginary coin and decide to turn 1, 2 and 3 into a loop.
First, I’m not sure quite why, but I move the code for 1, 2 and 3 down to the bottom of the code.
Public Function i2r(i As Integer) As String
If i = 4 Then
i2r = "IV"
ElseIf i = 5 Then
i2r = "V"
ElseIf i = 6 Then
i2r = "VI"
ElseIf i = 7 Then
i2r = "VII"
ElseIf i = 8 Then
i2r = "VIII"
End If
If i = 1 Then
i2r = "I"
ElseIf i = 2 Then
i2r = "II"
ElseIf i = 3 Then
i2r = "III"
End If
End Function
Just to make sure this hasn’t broken anything I switch back to the spreadsheet and recalc. I probably didn’t need to do this but it has been a long time since I’ve coded and I’m a bit nervous doing this. All of the tests still work.
Then I turn the 1,2 and 3 bits into a loop.
This is my first attempt:
Public Function i2r(i As Integer) As String
If i = 4 Then
i2r = "IV"
ElseIf i = 5 Then
i2r = "V"
ElseIf i = 6 Then
i2r = "VI"
ElseIf i = 7 Then
i2r = "VII"
ElseIf i = 8 Then
i2r = "VIII"
End If
i2r = ""
While i < 3 And i > 0
i2r = i2r + "I"
i = i - 1
End
End Function
I recalc the spreadsheet and it doesn’t work. I realise this when I look at the code and notice I put a END, rather than a WEND, to close off the While loop.
So, I pop back to the spreadsheet and press F9 to rerun the tests again.