Example of Optional

As a demonstration of Optional, we are going to create an in-memory student repository. This repository has a method to find students by their name, which, for convenience, will be considered the ID. The value returned by the method is Optional<Student>; this means that the response might or might not contain a Student. This pattern is basically one of the common scenarios for Optional.

At this point, the reader should be familiar with the TDD process. For the sake of brevity the complete Red-Green-Refactor process is skipped. Tests are going to be presented along with the implementation in a convenient order, which could not coincide with the order in a TDD iteration.

First of all, we need a Student class to represent ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.