Java Bootcamp – Workbooks and Challenges

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, 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 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:

  1. receives each element as a parameter.
  2. has an arrow that points to code.
  3. returns a boolean.

Screen Shot 2021-07-02 at 2.55.08 PM.png

Important: As you refactor, run the unit test to make sure there aren't bugs.

Good Luck

Feedback Summary
43 students





Written Reviews
There are no written reviews yet.