Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

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

// Avoidpublic 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");
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content