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

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 _.

主站蜘蛛池模板: 承德市| 仙游县| 涟水县| 桦南县| 江阴市| 石楼县| 苏尼特右旗| 金堂县| 汤原县| 广南县| 章丘市| 栾城县| 无锡市| 布拖县| 临汾市| 民权县| 临洮县| 涿州市| 嘉兴市| 深泽县| 陕西省| 淳安县| 宜城市| 平武县| 德阳市| 南平市| 嘉祥县| 汪清县| 凉山| 灵川县| 舟山市| 石棉县| 宜君县| 贡山| 洞头县| 宁都县| 长春市| 甘肃省| 平顺县| 玉林市| 铁力市|