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

DOCKER - No Space Left on Device // How to clean Docker on Linux

Sometimes Docker will simply claim to much space. Time for a clean up ;) docker system prune -a -f