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

if(myParam == null || myParam.toCharArray().length == 0){

In favor of that:

//.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

How To Resolve GIT Merge Conflicts with IntelliJ

Resolve a Merge Conflict in GIT with IntelliJ Let us assume you are using Bitbucket or a similar tool to administrate and host your GI...