0

Is it OK to pass Optional as a parameter to Java methods?

As for me it's bad because after passing Optional to the method, we create situation when method should do two things:

  1. Some logic when object is present
  2. Another logic that covers case when object is absent

For example:

public class Example {
    private String receiveSomeString(Optional<SomeReceiver> printer) {
        return printer
                .map(SomeReceiver::getA)
                .orElse("B");
    }

}
class SomeReceiver {
    public String getA(){
        return "A";
    };
}

As for me it's break Single Responsibility Principle (SRP) and method should do two things.

Is it correct?

Dmytro Melnychuk
  • 2,285
  • 21
  • 23
  • 1
    *"What do you think about it?"* -> opinion based questions are off-topic. – Tom Jun 25 '17 at 18:34
  • It's definitely kinda weird. `Optional` and streams are recent additions to Java. Most folks would just pass in a `SomeReciever` directly and check it for `null`. Also: make sure you always document behavior for `null` arguments. Throwing NPE is fine as long as the Java doc says "Throws NPE if this argument is null." – markspace Jun 25 '17 at 18:36
  • Yes, but passing nullable object and checking inside the method is a bad approach, because as I mention above it create situation when method should do two things. – Dmytro Melnychuk Jun 25 '17 at 18:38
  • Why is it a bad approach? `Optional` could be `null` here too, yet you don't check for it (nor document the NPE). – markspace Jun 25 '17 at 18:39
  • Using `map` and `orElse` splits the logic. And my example above show just simple example – Dmytro Melnychuk Jun 25 '17 at 18:59

0 Answers0