How to check if null is, and if it has a specific value, using an option in java?

Suppose I have this code in my project:

public List<T> getAll(Integer parameter) { if(parameter != null && parameter > -1) { // do something here } } 

My question is: how can I do a check with Optional instead of using if , or if there is one more thing I could use?

+6
source share
5 answers

Use Optional<Integer>

 public List<T> getAll(Integer paramter) { return Optional.ofNullable(parameter) .filter(p -> p > -1); } 

Optional<> is just an implementation of an optional template. Useful methods are also Optional<T>#orElse(T default) , which sets a default value if null exists,

If you are already interested, but cannot answer your doubts, please clarify in the comments. I will reply as soon as possible.

+3
source

The complementary design was inspired by monads, known from the world of functional programming. In this case, it may look like this:

 public List<T> getAll(Integer parameter) { return Optional.ofNullable(parameter) .filter(p -> p > -1) .map(p -> *some modification*) //this line is optional .orElseGet(() -> *some default value, probably an empty list*) } 

In this case, conditions are checked in the filter method. If the given Predicate does not match, the base Optional will be empty.

If you want to perform an operation on a base value, use the map method, providing it with a Function that should be applied to the element wrapped by Optional .

In the end, you can simply do something with ifPresent() , throw an orElseThrow exception orElseThrow or simply return the default value with orElse or orElseGet . Keep in mind that orElseGet accepts a Supplier instance that allows you to evaluate the default value lazily.

If you want to dig deeper, check out @ stuart-marks talk from Devoxx: https://www.youtube.com/watch?v=Ej0sss6cq14&t=2767s

In your case, there may not be a need for Optional. Only two methods. One with a parameter and the other without.

+18
source

You should not use Optional for such a case.

As Stuart Marks says in Advanced - Mother of all Bikeshess :

Rule number 4 . As a rule, it is a bad idea to create chaining methods that are optional for a particular purpose in order to get a value.

This creates unnecessary overhead without any improvement in reading and maintaining the code. Thus, you should not include your parameter in optional.

and

Rule number 6 . Avoid using options in fields, parameters, and method collections.

Avoid using options in method parameters

  • it really doesn’t work for setting parameters
  • forces sites to create options for everything:

    myMethod(Optional.of("some value"));

    myMethod(Optional.empty());

See also Why Java 8 Optionally Not Used in Arguments .

+7
source

You need to clearly understand what you expect from your method. Capabilities:

  • You want it to continue to work as before and handle the case when the client supplies zero
  • You want to change the method to accept Optional<Integer> as its parameter. The "no nulls" way is to do this and simply not use callers who throw zero - if they get a NullPointerException, this is their own mistake because they break the rules.

You do not need to work with streams or lambdas to work with optional (although, of course, you can).

You can simply write:

 public List<T> getAll(Optional<Integer> maybeParameter) { if(maybeParameter.isPresent() && maybeParameter.get() > -1) { // do something here } } 

Look at Optional other methods in the JavaDoc to find out how else this can be used.

If you do not want to change the signature of your method, you can use Optional.ofNullable() to turn Integer into Optional<Integer> :

 public List<T> getAll(Integer parameter) { Optional<Integer> maybeParameter = Optional.ofNullable(parameter); // work with the Optional here as before... } 

However, I ask a question about how this is done here. If your API is NULL, then handling it with Optional "behind the scenes" does not give benefits.

I find it best to use Optional to expose it as part of your API. If the parameter is optional, declare it as Optional , and do not handle zero (or better, use method overloading so that they don’t miss anything at all). If the return value cannot be set, enter the Optional return type, and not return null.

-one
source
 import java.util.Optional; public class ExampleNullCheck{ public static void main(String args[]) { Integer a = null; Optional<Integer> checkInt = Optional.ofNullable(a); System.out.println(checkInt.isPresent()); }//main }//class 
-2
source

Source: https://habr.com/ru/post/1012301/


All Articles