Using Java 8 Optional – Converting logic

  • A+

I'm trying to learn how to use Optional in Java - but this doesn't seem correct what I'm doing.

User user = null;  public AuthCheck(User user) throws Exception {     if (user == null) {         throw new Exception("No user!");     }     if (!(user.getStuff() != null && !user.getStuff().isEmpty())) {         throw new Exception("User has no stuff");     }     this.user = user; } 

This is how I tried to convert it using Optional:

Optional<UserOptional> user;  public AuthCheckOptional(Optional<UserOptional> user) throws Exception {     user.orElseThrow(() -> new Exception("No User!"));         .orElseThrow(() -> new Exception("User has no stuff"));      this.user = user; } 

I would of thought I wouldn't need two separate checks. Also I believe I've changed the logic here as the IsEmpty() isn't happening.

You don't want to use Optional as an input parameter; it's an anti-pattern. Check out this article on DZone.

What you can do to improve your code is as follows:

User user = null;  public authCheck(User user) {     Objects.requireNonNull(user, "No user!");      if (Objects.requireNonNull(user.getStuff(), "User has no stuff").isEmpty()) {         throw new RuntimeException("User has no stuff");     }      this.user = user; } 

(Method names should start with a lower case in Java.)

You could further condense it, but the question is whether the code would be any clearer.

There's nothing wrong with null, if used properly. It means "undefined", and we don't have non-null object references in Java, like there are in Kotlin or Scala.

But perhaps you could think a little bit about how User objects are created, so that you avoid this issue altogether. You could perhaps employ the Builder design pattern. More often than not, rethinking your code can avoid situations like these.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: