Search code examples
javafunctional-programmingoption-type

How to Write a Change Detector with Two Optionals in Functional Java?


Is there a functional way to write a change reporter for two optional variables?

The code is meant to detect value changes when moving from the value in Optional A to the value in Optional B with one quirk, that if Optional B is empty then we report a default value.

I want the following behavior:

    +------------+------------+---------+
    | Optional A | Optional B | Result  |
    +------------+------------+---------+
    | empty      | empty      | empty   |
    | empty      | y          | y       |
    | x          | empty      | default |
    | x          | y          | y       |
    | x          | x          | empty   |
    +------------+------------+---------+

I have a solution that looks like It should be simpler:

public Optional<String> reportChange(Optional<String> aOpt, Optional<String> bOpt) {
   if(aOpt.isPresent() && bOpt.isEmpty()) {
       return Optional.of(DEFAULT_VALUE);
   } else if (bOpt.isEmpty()){
       return Optional.empty();
   }
   return bOpt.flatMap(b -> {
       if (aOpt.isEmpty() || b.compareToIgnoreCase(aOpt.orElseThrow()) != 0) {
           return Optional.of(b);
       }
       return Optional.empty();
   });
}

What is the functional-programming way to write this?


Solution

  • Your code can be simplified to a simple conditional expression:

    public Optional<String> reportChange(Optional<String> aOpt, Optional<String> bOpt) {
        return aOpt.equals(bOpt)
           ? Optional.empty()
           : Optional.of(bOpt.orElse(DEFAULT_VALUE));
    }