So, my question is - are those changes to Optional adding some benefits ...

Well there are definitely advantages and disadvantages for both approaches:

Looking from the Optional side, the main "plus" is that you eliminate a major source of bugs; i.e. NPE's caused by not dealing with a possible returned null correctly. The main "minuses" are the verbosity of code that uses Optional, and that it doesn't actually eliminate all bugs; e.g. if you call Optional.get on an "empty" Optional you will get an exception.

Other Q&A's go into more detail:

  • Null check vs Optional is present check
  • Uses for Optional
  • Optional vs. null. What is the purpose of Optional in Java 8?
  • Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

... or we are just following fashion without thinking.

That is a different question!

Now I imagine some people may be using Optional without thinking, but I don't see much evidence of that. It is clear that there are advantages AND disadvantages, and that thought is required.

So you should really be asking (yourself!) if >>you<< just following fashion without thinking? Or to put it another way, are you just treating this as a (so-called) "best practice", or are you making a reasoned choice between the two approaches depending on the context?


I have got a suggestion to rewrite everything [in my example] using Optional.

Here's what I suggest.

  1. Create a branch in your version control system.
  2. In the branch, change your API method to use Optional, and change all of the places in your code that use the API method.
  3. Make a judgement: has this improved things? was the effort worth it?
  4. If the API is currently or going to used by other people's code, ask their opinions too.
  5. Decide whether to proceed or not, implement decision, and move on to the next issue.

If that sounds like too much work, another option is to quietly ignore that suggestion.

Either way, we (the StackOverflow community) can't decide for you. We don't have the context1, and even if we did, there would be a range of opinions and no clear correct answer.


1 - For instance, what is the likelihood of there being no locale, and no determinable language. What the application as a whole should do about it? Should it bail out? Should it substitute a default? Could the default be substituted ... here? We can't see "the big picture".

Answer from Stephen C on Stack Overflow
Top answer
1 of 2
2

So, my question is - are those changes to Optional adding some benefits ...

Well there are definitely advantages and disadvantages for both approaches:

Looking from the Optional side, the main "plus" is that you eliminate a major source of bugs; i.e. NPE's caused by not dealing with a possible returned null correctly. The main "minuses" are the verbosity of code that uses Optional, and that it doesn't actually eliminate all bugs; e.g. if you call Optional.get on an "empty" Optional you will get an exception.

Other Q&A's go into more detail:

  • Null check vs Optional is present check
  • Uses for Optional
  • Optional vs. null. What is the purpose of Optional in Java 8?
  • Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

... or we are just following fashion without thinking.

That is a different question!

Now I imagine some people may be using Optional without thinking, but I don't see much evidence of that. It is clear that there are advantages AND disadvantages, and that thought is required.

So you should really be asking (yourself!) if >>you<< just following fashion without thinking? Or to put it another way, are you just treating this as a (so-called) "best practice", or are you making a reasoned choice between the two approaches depending on the context?


I have got a suggestion to rewrite everything [in my example] using Optional.

Here's what I suggest.

  1. Create a branch in your version control system.
  2. In the branch, change your API method to use Optional, and change all of the places in your code that use the API method.
  3. Make a judgement: has this improved things? was the effort worth it?
  4. If the API is currently or going to used by other people's code, ask their opinions too.
  5. Decide whether to proceed or not, implement decision, and move on to the next issue.

If that sounds like too much work, another option is to quietly ignore that suggestion.

Either way, we (the StackOverflow community) can't decide for you. We don't have the context1, and even if we did, there would be a range of opinions and no clear correct answer.


1 - For instance, what is the likelihood of there being no locale, and no determinable language. What the application as a whole should do about it? Should it bail out? Should it substitute a default? Could the default be substituted ... here? We can't see "the big picture".

2 of 2
0

I would say Optional is good when your code knows how to deal with the null situation. For example you can write

 public String helloWorld(Optional<Long> input){
     String toReturn = "Hello "+ input.orElse("0")+ " times";
     return toReturn;
 }

However, if you are interfacing with legacy code and those functions expect null inputs, which force you to write something like

if(someOptional.isPresent()){
       return somevalue;
} else{
       return null;
 }

In the above case, Optional does not bring you more than using null only. In this case I would use null over Optional.

Discussions

java - Optional Type returns a null value - Stack Overflow
Now you have an actual Optional object attached to reference testString instead of null. Java 10 would allow the even shorter · private var testString= Optional.empty() ; If you already have a String value to start with (let's call it originalString), there are 3 main options: More on stackoverflow.com
🌐 stackoverflow.com
Optional vs. null. What is the purpose of Optional in Java 8? - Stack Overflow
In Java 8 you can return an Optional instead of a null. Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPr... More on stackoverflow.com
🌐 stackoverflow.com
Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
The idea with Optional is to force the user of the method to handle the output straight away. Being able to pass that value around is against the point of using an Optional in the first place. For example, you have a method that calls an API. If it returns empty, you should either throw an exception, or fill in some default value. If it returns a value, then unpack it. You should not have an Optional going forward. More on reddit.com
🌐 r/java
285
123
March 25, 2023
Method return Optional or null?
If you think users of your library won't always remember to check for null, use an Optional. If null handling is very important, use an Optional. If null is a valid return that does not indicate unavailability or failure, use an Optional. I come from the world of functional programming, so I would say always use an optional. It enforces the check and makes sure people handle the errors. More on reddit.com
🌐 r/java
54
4
March 25, 2017
Top answer
1 of 9
23

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work.

Without Optional, every reference in your code is like an unexploded bomb. Accessing it may do something useful, or else it may terminate your program wth an exception.

With Optional and without null, every access to a normal reference succeeds, and every reference to an Optional succeeds unless it's unset and you failed to check for that. That is a huge win in maintainability.

Unfortunately, most languages that now offer Optional haven't abolished null, so you can only profit from the concept by instituting a strict policy of "absolutely no null, ever". Therefore, Optional in e.g. Java is not as compelling as it should ideally be.

2 of 9
23

An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much more useful is the ability to delay or avoid checking for failure, and to easily compose many operations that may fail.

Consider if you had your optional variable from your example code, then you had to perform two additional steps that each might potentially fail. If any step along the way fails, you want to return a default value instead. Using Optionals correctly, you end up with something like this:

return optional.flatMap(x -> x.anotherOptionalStep())
               .flatMap(x -> x.yetAnotherOptionalStep())
               .orElse(defaultValue);

With null I would have had to check three times for null before proceeding, which adds a lot of complexity and maintenance headaches to the code. Optionals have that check built in to the flatMap and orElse functions.

Note I didn't call isPresent once, which you should think of as a code smell when using Optionals. That doesn't necessarily mean you should never use isPresent, just that you should heavily scrutinize any code that does, to see if there is a better way. Otherwise, you're right, you're only getting a marginal type safety benefit over using null.

Also note that I'm not as worried about encapsulating this all into one function, in order to protect other parts of my code from null pointers from intermediate results. If it makes more sense to have my .orElse(defaultValue) in another function for example, I have much fewer qualms about putting it there, and it's much easier to compose the operations between different functions as needed.

🌐
Baeldung
baeldung.com › home › java › java optional as return type
Java Optional as Return Type | Baeldung
January 8, 2024 - The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we’re likely to check if the value is missing, leading to fewer NullPointerExceptions in the applications.
🌐
A N M Bazlur Rahman
bazlur.ca › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 27, 2023 - By wrapping a potentially null ... For example, if you have a method that returns a value that might be null, you can return an Optional instead and then use Optional methods to access the value safely....
🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - For example, for the findByUsername method, we pass username and it returns related user from database. But, such user may not exist. In this case, we better return User wrapped inside Optional to handle nulls better. In this article, I talked about null handling in Java with Optionals.
🌐
Scaledcode
blog.scaledcode.com › blog › effective-java › return_optionals_judiciously
Effective Java! Return Optionals Judiciously
December 23, 2020 - Something of note, an Optional is just another class and thus you can return null from methods that return Optionals. While the language allows this unfortunately you should not do this.
Find elsewhere
🌐
Todaysoftmag
todaysoftmag.com › article › 1321 › java-8-optional-is-not-just-for-replacing-a-null-value
TSM - Java 8 Optional is not just for replacing a null value
Optional allows you to handle all the possible error conditions without an Exception or nested if/else logic. static Optional getFirstSecondThird(Optional nested) { return nested // could be non-present .map(x -\> x.first) // could be null .map(x ...
🌐
Hacker News
news.ycombinator.com › item
Why is Optional better then throwing an exception or returning a null? The way... | Hacker News
January 30, 2017 - The way I see it it's like this: · Optional<Integer> num = getSomeRiskyNumber(); if (!num.isPresent()) return ... code to bubble up a blank optional vs
🌐
Medium
medium.com › thefreshwrites › java-optional-and-either-handling-null-values-and-representing-two-possible-values-6a477a0fe189
Java Optional and Either: Handling Null Values and Representing Two Possible Values | by Samuel Catalano | Mar, 2023 | Medium | The Fresh Writes
March 10, 2023 - In this example, optionalName is an Optional that contains a value if name is not null, otherwise it is empty. The orElse() method returns the value if it is present, otherwise it returns the default value “Unknown”. Java Either is a class ...
Top answer
1 of 3
63

In practice, why is this useful?

For example let's say you have this stream of integers and you're doing a filtering:

int x = IntStream.of(1, -3, 5)
                 .filter(x -> x % 2 == 0)
                 .findFirst(); //hypothetical assuming that there's no Optional in the API

You don't know in advance that the filter operation will remove all the values in the Stream.

Assume that there would be no Optional in the API. In this case, what should findFirst return?

The only possible way would be to throw an exception such as NoSuchElementException, which is IMO rather annoying, as I don't think it should stop the execution of your program (or you'd have to catch the exception, not very convenient either) and the filtering criteria could be more complex than that.

With the use of Optional, it's up to the caller to check whether the Optional is empty or not (i.e if your computation resulted in a value or not).

With reference type, you could also return null (but null could be a possible value in the case you filter only null values; so we're back to the exception case).

Concerning non-stream usages, in addition to prevent NPE, I think it also helps to design a more explicit API saying that the value may be present or not. For example consider this class:

class Car {
   RadioCar radioCar; //may be null or not 
   public Optional<RadioCar> getRadioCar() {
        return Optional.ofNullable(radioCar);
   }
}

Here you are clearly saying to the caller that the radio in the car is optional, it might be or not there.

2 of 3
32

When Java was first designed it was common practice to use a special value, usually called null to indicate special circumstances like I couldn't find what you were looking for. This practice was adopted by Java.

Since then it has been suggested that this practice should be considered an anti-pattern, especially for objects, because it means that you have to litter your code with null checks to achieve reliability and stability. It is also a pain when you want to put null into a collection for example.

The modern attitude is to use a special object that may or may not hold a value. This way you can safely create one and just not fill it with anything. Here you are seeing Java 8 encouraging this best-practice by providing an Optional object.

🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
You can create an optional object from a nullable value using the static factoy method Optional.ofNullable. The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed.
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
January 16, 2024 - Java 9 introduces the or() method that returns another Optional lazily if our Optional is empty.
🌐
Medium
medium.com › javarevisited › null-check-vs-optional-are-they-same-c361d15fade3
Null Check vs Optional? What's the difference ? How to use Optional | Javarevisited
November 4, 2020 - The main point of Optional is to indicate the absence of a value (i.e null value ) while returning value for the function. It was meant to clarify the intent to the caller. I believe the problem arises when Optional is used in the same way as ...
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
*/ public Human(String name, String address, Set<Human> friends, LocalDate birthDate){ this.name = Objects.requireNonNull(name).trim(); if (this.name.length() == 0){ throw new IllegalArgumentException("Name is empty."); } this.address = Objects.requireNonNull(address).trim(); this.friends.addAll(Objects.requireNonNull(friends)); //defensive copy this.birthDate = birthDate; //immutable, no need to copy } //..elided /** Never null or empty. */ public String getName() { return name; } /** Might be an empty String. */ public String getAddress() { return address; } /** Might be an empty Set. */ public Set<Human> getFriends() { //make sure the caller can't modify the private Set return Collections.unmodifiableSet(friends); } /** May or may not be present. The returned Optional object is itself never null!
🌐
Reddit
reddit.com › r/java › why exactly does brian goetz not recommend the use of optional everywhere a value could be null?
r/java on Reddit: Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
March 25, 2023 - When your method returns ‘Optional’ you control this method. But you can’t control input parameters for your method and it means that it can be invoked with ‘null’ instead of ‘Optional.empty()’ for example. ... This is true; however, when your method parameters use Optional, the method signature itself is explicit about what it accepts. No need to reference javadoc, source code, or provide clever hints using the parameter name to see what parameters allow null.
🌐
Faun
faun.pub › working-on-null-elegantly-with-java-optional-62f5e65869c5
Working on Null Elegantly with Java Optional
July 21, 2019 - Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null.