237. Do not use Optional in constructor args

The do not use category continues with another scenario that is against the intention of using Optional. Keep in mind that Optional represents a container for objects; therefore, Optional adds another level of abstraction. In other words, improper use of Optional simply adds extra boilerplate code.

Check the following use case of Optional that shows this (this code violates the previous Do not use Optional for fields section):

// Avoid
public class Book {

// cannot be null
private final String title;

// optional field, cannot be null
private final Optional<String> isbn;

public Book(String title, Optional<String> isbn) {
this.title = Objects.requireNonNull(title,
() -> "Title cannot be null");

if (isbn == null) {
this.isbn = Optional.empty();
} else {
this.isbn = isbn;
}

// or
this.isbn = Objects.requireNonNullElse(isbn, Optional.empty());
}

public String getTitle() {
return title;
}

public Optional<String> getIsbn() {
return isbn;
}
}

We can fix this code by removing Optional from the fields and from the constructor arguments, as follows:

// Prefer
public class Book {

private final String title; // cannot be null
private final String isbn; // can be null

public Book(String title, String isbn) {
this.title = Objects.requireNonNull(title,
() -> "Title cannot be null");
this.isbn = isbn;
}

public String getTitle() {
return title;
}

public Optional<String> getIsbn() {
return Optional.ofNullable(isbn);
}
}

The getter of isbn returns Optional. But do not consider this example as a rule for transforming all of your getters in this way. Some getters return collections or arrays, and, in that case, they prefer returning empty collections/arrays instead of Optional. Use this technique and keep in mind the statement of Brian Goetz (Java's language architect):

"I think routinely using it as a return value for getters would definitely be over-use."
 Brian Goetz
..................Content has been hidden....................

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