官术网_书友最值得收藏!

Ensuring termination

We are not quite done yet because our function might loop indefinitely. Imagine that you always spend more than what you earn. You will never be able to save enough to retire, even if you live a million years! Here is a unit test highlighting this:

"RetCalc.nbOfMonthsSaving" should {
"calculate how long I need to save before I can retire" in {...}

"not crash if the resulting nbOfMonths is very high" in {...}

"not loop forever if I enter bad parameters" in {
val actual = RetCalc.nbOfMonthsSavingV2(
interestRate = 0.04 / 12, nbOfMonthsInRetirement = 40 * 12,
netIncome = 1000, currentExpenses = 2000, initialCapital = 10000)
actual should === (Int.MaxValue)
}
}

We decided to use a special value Int.MaxValue to indicate that nbOfMonths is infinite. This is not very pretty, but we will see in the next chapter how we can model this better with Option or Either. This is good enough for now.

To make the test pass, we just need to add an if statement:

def nbOfMonthsSaving(interestRate: Double, nbOfMonthsInRetirement: Int,
netIncome: Int, currentExpenses: Int, initialCapital: Double): Int = {
@tailrec
def loop(nbOfMonthsSaving: Int): Int = {...}

if (netIncome > currentExpenses)
loop(0)
else
Int.MaxValue
}
主站蜘蛛池模板: 莆田市| 广州市| 福建省| 常宁市| 秦皇岛市| 南郑县| 桦川县| 达孜县| 彝良县| 兴国县| 乌苏市| 福鼎市| 牟定县| 襄垣县| 阿克苏市| 谷城县| 长岛县| 同心县| 姚安县| 邹城市| 衢州市| 承德县| 积石山| 新丰县| 平谷区| 麟游县| 盐城市| 巴中市| 普洱| 尚义县| 桓台县| 邵阳市| 湘阴县| 合川市| 中阳县| 五原县| 香港| 若尔盖县| 开阳县| 浦城县| 亚东县|