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.
Part 1: Introduction
Part 2: Getting Started
Part 3: Social Unit Tests
Part 4: Heart Container Implementation
Part 5: Test Data Builders
Part 6: Safe Refactoring
Part 7: Basic Player Health
Part 8: An Event Driven UI
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