Movie Store – Part 3
Test-Driven Development: write tests before writing code.
Unit testing results in modular code. Modular code is:
- easy to test.
- immune to bugs.
- easy to understand.
- scalable.
Task 1: Unit Testing
1. Create a test that fails
Write a unit test named sellMovieTest
. Inside, sell The Godfather
and check if the store still contains the movie. Hint: use assertFalse
.
Inside Store.java
, write code to make the test fail.
/**
* Function name: sellMovie
* @param name (String)
*
* Inside the function:
* //nothing
*/
2. Make the test pass
/**
* Function name: sellMovie
* @param name (String)
*
* Inside the function:
* 1. loop runs through the size of the ArrayList.
* 2. removes the movie that matches the name passed in.
*/
3. Refactor
Can sellMovie
be simpler?
Yes. removeIf
is a better way to remove elements. It removes elements that "match a predicate". In other words, elements for which the returned boolean
is true
.
ArrayList.removeIf(Lambda Expression)
The lambda expression for removeIf
:
- receives each element as a parameter.
- has an arrow that points to code.
- returns a
boolean
.
Important: As you refactor, run the unit test to make sure there aren't bugs.
4. Refactor
Can sellMovie
be simpler?
- Yes. If the code is one line, you can omit the curly brackets and the
return
keyword. Java knows you intend to return aboolean
.
Important: As you refactor, run the unit test to make sure there aren't bugs.
5. Refactor
Can sellMovie
be simpler? No. Refactoring complete.