Shopping Cart – 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
1. Create a test that fails
Write a unit test named removedItemTest
. removedItemTest
asserts that an item gets removed after being sold.
Inside Cart.java
, write code to make the test fail.
/** * Function name: remove * @param name * * Inside the function: * 1. nothing */
2. Make the test pass
Write code inside Store.java
to make the test pass.
/** * Function name: remove * @param name * * Inside the function: * 1. loop runs through the size of the ArrayList. * 2. removes the item that matches the name passed in. */
3. Refactor
- Can
remove
be simpler?
Yes. removeIf
offers a better way to remove elements. It removes elements that match the "predicate". In other words, elements for which the boolean
is true
.
removeIf
expects a Lambda Expression.
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.
Good Luck
Feedback Summary
4.7
43 students
5
91%
4
2%
3
0%
2
0%
1
7%
Written Reviews
There are no written reviews yet.