240. Do not use Optional to return empty or null collections or arrays

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:

// Avoid
public 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);

// Avoid
public Optional<Book[]> fetchBooksByYear(int year) {
// fetching the books may return null
Book[] books = ...;

return Optional.ofNullable(books);
}

Optional<Book[]> books = author.fetchBooksByYear(2021);

We can clean this code by removing the unnecessary Optional and then rely on empty collections (for example, Collections.emptyList(), emptyMap(), and emptySet()) and arrays (for example, new String[0]). This is the preferable solution:

// Prefer
public List<Book> fetchBooksByYear(int year) {
// fetching the books may return null
List<Book> books = ...;

return books == null ? Collections.emptyList() : books;
}

List<Book> books = author.fetchBooksByYear(2021);

// Prefer
public Book[] fetchBooksByYear(int year) {
// fetching the books may return null
Book[] books = ...;

return books == null ? new Book[0] : books;
}

Book[] books = author.fetchBooksByYear(2021);

If you need to distinguish between a missing and an empty collection/array then throw an exception for the missing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.246.245