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. In this example we get rid of this:

if(myParam == null || myParam.toCharArray().length == 0){
   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"));


Kommentare

Beliebte Posts