Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I would like to know about the meaningful usage of Optional orElseGet

First, let me clarify that this is not a question asking "how to use" or "differences" of this method.

I have a query to lookup one object by ID in DB.

If this ID is invalid, no object will be returned, which will result in an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To prevent this from happening, I wrapped the return object in Optional, and the problem was solved.

At that moment, a new problem arose.

In the context of retrieving this object, I found that I had only two options.

  1. Since there is an object returned, the object is used normally.

  2. There is no object returned, so there is nothing we can do other than null or Throw.

My return object is UserEntity.

i.e. when i use the value

UserEntity user = getUser().orElstGet(null);

or

UserEntity user = getUser().orElstThrow(...);

I don’t think there is anything else that can be done.

If the object I wanted didn’t come in the response, UserEntity user; There is no object other than null that can be contained in .

Obviously something is wrong, or I think there is a more correct usage.

can you give me some advice?

>Solution :

You don’t exactly give enough context to give a meaningful specific answer.

For users, a sensible usage could be

UserEntity user = userRepo.getUser(userId).orElseGet(() -> userRepo.getGuestUser());

It really depends on the use case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading