finner

finner

Using Optional in Java

During a recent code review I came across this scenario:

Code in review

if (input.getValue() != null) {
   return Arrays.asList(value);
}  else {
   return input.getValues().stream().map(this::parseValues).collect(Collectors.toList())
}

And I suggested (in a compassionate way :grin: ) that we use Optional to treat the null value, so my suggestion was something like:

return Optional.ofNullable(input.getValue()).map(Arrays::asList)
       .orElseGet(input.getValues().stream().map(this::parseValues).collect(Collectors.toList()));

And I thought I was being very clever.

But then I realised it’s harder to understand the logic in this version. At least the if is a clear intent.
So I read up some more on Optional.
The Optional container allows us to perform logic including chaining map, flatMap, filter etc based on a value that may or may not be present. But this is not the real intention of Optional.

Optional is mainly used to represent attributes in an object that may be null or a method in an API that could return a null.

Consider a Person.
Everyone has a name, an age and a gender but may not have a car so we could define a class as follows:

class Person {
   private String name;
   private int age;
   private boolean female;
   private Optional<Car> car;
}

From this declaration it’s obvious that not everyone has a car and so the caller would then treat the car attribute appropriately.

My take away is the following:

Optional is not a replacement for occurrences if (x != null)

Any heavy users of Optional around?
Tips and/or suggestions would be very much appreciated.

Most Liked

finner

finner

Today I came across a very elegant use (IMHO) of Optional at work.
Consider the same person as above with a date of birth attribute:

public class Person {
   private String name;
   private String dob;

   // getters & setters etc etc (yep Java is verbose !!!!)
}

Now say you want to get that dob value into a Date object and do weird and wonderful date calculations.
You could use Optional like this:


// if you expect dob to be a string in the format yyyy-mm-dd
LocalDate birthday = Optional.ofNullable(persone.getDob())
    .map(LocalDate::parse)
    .orElse(null);  // or whatever

// or if the dob is in a different format, for example dd-MM-yyyy
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate  d = Optional.ofNullable(p.getDob())
                .map(dob -> LocalDate.parse(dob, formatter))
                .orElse(null);

Now you have a LocalDate instance to play with.

In fact, once you have an Optional instance you have the following stream operators available

  • map
  • flatMap
  • filter

flatMap can be used to compose Optionals

public int ageDifference(Optional<Person> older, Optional<Person> younger) {
     return older.flatMap(o -> younger.map(y -> calAgeDifference(o.getDob(), y.getDob())); 
}

Quite cool :sunglasses:

Just thought I’d share :slight_smile:

finner

finner

cheers @AstonJ -
it’s actually good practice for me to help reinforce the learning by posting. Although at my age I will have forgotten it by end of week.
… so what were we talking about again … ?

AstonJ

AstonJ

:rofl: :rofl: :rofl:

I am just as bad - though I think a modern world is partly to blame - we are bombarded with information almost constantly now, imagine living a few thousand years ago before TV/Radio/Computers/Internet. Probably would have been quite serene and peaceful :smiley:

Funny thing is I read that article… and forgot most of it :rofl:

Popular Backend topics Top

AstonJ
Another BEAM language… The Hamler Programming Language Hamler is a strongly-typed language with compile-time typechecking and built-in...
New
ErlangSolutions
Hi this week it’s Code Mesh V when London’s leading alternative tech conference goes virtual for the first time. Talks are set for both U...
New
DevotionGeo
How Dgraph was running out of memory for some users, and how Go’s Garbage collector wasn’t enough, and Dgraph team used jemalloc to manag...
New
Jsdr3398
I just thought of this. Are there any disadvantages when making your server in Assembly (other than having to learn a bunch of stuff :ro...
New
PragmaticBookshelf
Build highly interactive applications without ever leaving Elixir, the way the experts do. Let LiveView take care of performance, scalabi...
New
GermaVinsmoke
Reading Programming Elixir 1.6 book, I’ve completed part 1 of the book. Now I’m thinking of reading Elixir in Action. What do you all sug...
New
Cellane
I’ve been asked by my supervisors at work to finally give everyone in the team presentation about “that Elixir thing you can’t seem to sh...
New
PragmaticBookshelf
Build efficient applications that exploit the unique benefits of a pure functional language, learning from an engineer who uses Haskell t...
New
ManningBooks
Effectively reading and understanding existing code is a developer’s superpower. In this book, you’ll master techniques for code profilin...
New
PragmaticBookshelf
Leverage Elixir and the Nx ecosystem to build intelligent applications that solve real-world problems in computer vision, natural languag...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1016 16836 371
New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
Seems like a lot of people caught it - just wondered whether any of you did? As far as I know I didn’t, but it wouldn’t surprise me if I...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1122 25120 742
New
AstonJ
Saw this on TikTok of all places! :lol: Anyone heard of them before? Lite:
New
PragmaticBookshelf
Author Spotlight Jamis Buck @jamis This month, we have the pleasure of spotlighting author Jamis Buck, who has written Mazes for Prog...
New
PragmaticBookshelf
Author Spotlight Rebecca Skinner @RebeccaSkinner Welcome to our latest author spotlight, where we sit down with Rebecca Skinner, auth...
New
AstonJ
If you want a quick and easy way to block any website on your Mac using Little Snitch simply… File &gt; New Rule: And select Deny, O...
New
AstonJ
Chris Seaton, the creator of TruffleRuby has died. It appears from suicide :cry: He left this note on Twitter on the weekend: And one...
New
PragmaticBookshelf
Author Spotlight: Tammy Coron @Paradox927 Gaming, and writing games in particular, is about passion, vision, experience, and immersio...
New