In part 4 we’ll make progress by exposing some state information on the Heart class and chipping away at the implementation of the HeartContainer’s Replenish method.
In the previous video we reached a roadblock while writing HeartContainer’s Replenish method. In order to evenly distribute numberOfHeartPieces (the value passed into Replenish) evenly across HeartContainers’s list of hearts, we needed more information from the Heart class. More specifically, we needed access to the current number of heart pieces that the each of the heart has.
To solve this, we added a calculated property called numberOfHeartPieces to Heart that derives it’s value from Heart‘s image.fillAmount property. Although the calculation was simple, we allowed the test-driven development process to drive the creation of this property.
With numberOfHeartPieces available on the Heart class we were able to complete HeartContainer’s Replenish method. This iteration of the implementation required a bit more intelligence. It keeps a tally of the remaining number of heart pieces to be replenished by decrementing a temporary variable on each iteration of the loop. When the temporary variable reaches 0 the loop breaks.
- Added numberOfHeartPieces property to Heart, which calculates its value from _image.fillAmount
- Introduced some intelligence to HeartContainer’s Replenish method
- Add new TODO items to our list
Lessons & Takeaways
- Test-Driven Development doesn’t guarantee the best implementation on the first try
- Using Test-Driven Development improves productivity by keeping you focused
- You should always take the time to remove magic numbers
- Always rerun your tests after refactoring