Greeting
String Calculater
Roman Numbers
For example, the romanToDecimal() method which converts Roman numeral
into decimal
is like below.
fun romanToDecimal(roman: String): Int {
if (roman.isEmpty()) return 0
return roman
.toCharArray()
.mapIndexed { i, c ->
getSignOfCharacter(i, roman) * romanValue[c]!!
}.sum()
}
fun getSignOfCharacter(i: Int, roman: String) =
if (i < roman.indices.last && romanValue[roman[i]]!! < romanValue[roman[i + 1]]!!) -1 else 1
And this is the code doing exactly the same without TDD
fun romanToDecimal(roman: String): Int {
var sum = 0
for (i in roman.indices.first until roman.indices.last) {
val cur = roman[i]
val next = roman[i + 1]
if (cur == 'I' && (next == 'V' || next == 'X'))
sum -= 2 * romanValue['I']!!
if (cur == 'X' && (next == 'L' || next == 'C'))
sum -= 2 * romanValue['X']!!
if (cur == 'C' && (next == 'D' || next == 'M'))
sum -= 2 * romanValue['C']!!
}
for (c in roman.toCharArray()) {
sum += romanValue[c]!!
}
return sum
}
The former code looks simpler and is easier to understand developer's intention.
Among the TDD practice projects I've implemented,
the average production code is 21.6 lines, whereas the test code is 43.6 lines.
This lessons the vulnerability of malfunction.
And the test has higher quality than of made after implementing production codes.