September 2019
Intermediate to advanced
816 pages
18h 47m
English
Furthermore, in the do not use category, let's tackle the usage of Optional as the return type that wraps an empty or null collection or array.
Returning Optional that wraps an empty or null collection/array may be comprised of a clean and lightweight code. Check out the following code that shows this:
// Avoidpublic Optional<List<Book>> fetchBooksByYear(int year) { // fetching the books may return null List<Book> books = ...; return Optional.ofNullable(books);}Optional<List<Book>> books = author.fetchBooksByYear(2021);// Avoidpublic Optional<Book[]> fetchBooksByYear(int year) { // fetching the books may return null Book[] books = ...; return Optional.ofNullable(books); ...