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

Refactoring the production code

In the TDD approach, it is common to refactor the code once we have passing tests. If our test coverage is good, we should not have any fear of changing the code, because any mishap should be flagged by a failing test. This is known as a Red-Green-Refactor cycle.

Change the body of futureCapital with the following code:

def futureCapital(interestRate: Double, nbOfMonths: Int, netIncome: Int, currentExpenses: Int, initialCapital: Double): Double = {
val monthlySavings = netIncome - currentExpenses
(0 until nbOfMonths).foldLeft(initialCapital)(
(accumulated, _) => accumulated * (1 + interestRate) +
monthlySavings)
}

Here, we have inlined the nextCapital function in the foldLeft call. In Scala, we can define an anonymous function using the syntax:

(param1, param2, ..., paramN) => function body.

We saw earlier that the month parameter in nextCapital was not used. In an anonymous function, it is a good practice to name any unused parameter with _. A parameter named _ cannot be used in the function body. If you try to replace the _ character with a name, IntelliJ will underline it. If you hover the mouse over it, you will see a popup stating Declaration is never used. You can then hit Alt + Enter and choose to remove the unused element to automatically change it back to _.

主站蜘蛛池模板: 苍梧县| 澎湖县| 安国市| 建宁县| 江安县| 易门县| 桐柏县| 宁陵县| 苗栗县| 和平区| 泸州市| 和田市| 理塘县| 洱源县| 边坝县| 咸宁市| 顺昌县| 天津市| 射阳县| 徐水县| 永登县| 贞丰县| 门源| 绥中县| 兴和县| 安图县| 比如县| 临漳县| 五指山市| 左贡县| 金山区| 游戏| 南召县| 章丘市| 山东省| 南康市| 台南县| 富宁县| 金山区| 洱源县| 舒城县|