Donnerstag, 3. Mai 2018

Java Optional Example

Some people say that Optionals should only be used for API designs.

I think there is more to it and we can modernize our code. See this Nullpointer Exception. In this example we get rid of this:

//myList = null;
myList.add(myParam);


In favor of that:

Optional.ofNullable(myParam).ifPresent(myList::add);
//.of(myParam) would have thrown a Nullpointer if not present...

And for Exceptions, we get rid of this:

if (token == null) {
    throw new MyException("message");

}

In favor of that:


Optional.ofNullable(token).orElseThrow(() -> new MyException("message"));


Keine Kommentare:

Kommentar veröffentlichen

NEW BLOG! http://cleancode.consulting/

Dear Reader, This Blog is closed and remains as an archive. Please find our new Blog at  http://cleancode.consulting/