Return Optional instead of null
See original GitHub issueReturn Optional
instead of null everywhere, eg. in getValue()
calls.
Enable this
String msg = textInput.getValue().map(value -> "Hello " + value + "!").orElseGet("Don't be shy");
greeting.setText(msg);
instead of forcing our users to do this:
String value = textInput.getValue();
if (value == null || value.isEmpty()) {
greeting.setText("Don't be shy");
} else {
greeting.setText("Hello " + value + "!");
}
Null checks are a code smell in Java 8, and forcing if-else checking opens up the door for bugs.
Issue Analytics
- State:
- Created 7 years ago
- Comments:22 (22 by maintainers)
Top Results From Across the Web
Optional vs. null. What is the purpose of Optional in Java 8?
In Java 8 you can return an Optional instead of a null . Java 8 documentation says that an Optional is "A container...
Read more >Null Check vs Optional? Are they same? - Medium
The main point of Optional is to indicate the absence of a value (i.e null value ) while returning value for the function....
Read more >Why is using an optional preferential to null-checking the ...
Optional is used with the convention that methods with return type Optional never return null and usually also with the (less strong) convention...
Read more >Chapter 10. Using Optional as a better alternative to null
When a value is present, the Optional class just wraps it. Conversely, the absence of a value is modeled with an “empty” optional...
Read more >Guide To Java 8 Optional | Baeldung
This method returns true if the wrapped value is not null. ... However, instead of taking a value to return if the Optional...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
For example
Component.getId()
returnsOptional
whileComponent.setId()
takes String. This duality breaks the Java Bean spec and also borks Kotlin’sproperty
mechanism and hence Kotlin thinks there is just a read-only propertyid
of typeOptional<String>
- it ignores the setter since it is of different type.I believe Optional is a misuse in this case since according to https://blog.jetbrains.com/idea/2017/08/code-smells-null/ this is
In this case the use of Optional is discouraged.
I’m going to merge this issue to #3801 in case we ever get to improve the APIs or add features for better reactive/functional programming support.