0

I am having a variable (testvariable) according to the isNull of the variable I need to make a method call as below

if (testvariable != null) 
    method(testvariable);
 else 
    method();

What is the best way to simplify the code in Optional

Ivar
  • 6,138
  • 12
  • 49
  • 61
Kishore Chandran
  • 457
  • 4
  • 12
  • 6
    Optional isn't designed to avoid or replace null checks. Your code is absolutely fine. – JB Nizet Aug 23 '19 at 11:50
  • 2
    `Optional.ofNullable(testVariable).ifPresentOrElse(this::method, this::method)` (but it's not what Optional is for) – Andrew Tobilko Aug 23 '19 at 11:52
  • Please leave your code like it is, and do not use Optional for this. Optional is not meant to be a replacement for `if`. Part of being a good programmer is knowing how to write the most readable code possible, so that others can work with it once you are no longer available. – VGR Aug 23 '19 at 11:54

1 Answers1

4

Given that your method function returns a value (is not void), you can use the map and orElseGet functions, like this:

return Optional.ofNullable(testVariable)
    .map(tv -> method(tv))
    .orElseGet(() -> method());

The map function transforms your optional to contain the return value of method, but only if the optional contains a value. If testVariable was null, then the result will be retrived from the function passed to the orElseGet method.

If method returns void, then don't use Optional. Optional is best used to model the presence or absence of a value.

marstran
  • 26,413
  • 5
  • 61
  • 67