-1

if you have a method like this in java 8, is it correct to wrap the argument in an Optional? What is the best practice when the argument can be null? Worth to mention that argument "c" is coming from a source that I cannot change to Optional from there.

public String isSomething(c) {  
    if(c != null) {
        return ("something".equals(c))? "YES" : "NO";
    }

    return null;        
}
Michael
  • 41,989
  • 11
  • 82
  • 128
Shilan
  • 813
  • 1
  • 11
  • 17
  • 2
    Possible duplicate of [Why should Java 8's Optional not be used in arguments](https://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments) – Sotirios Delimanolis Mar 22 '18 at 14:54

2 Answers2

4

The best practice is not to declare that an “argument can be null”, when in reality, the method doesn’t do anything useful when the argument is null.

Your code is the perfect example of an anti-pattern. If the argument is null, your method returns null, to let the caller’s code fail at some later time, in the worst case, at a point where it is impossible to trace back where the null reference appeared the first time.

If your method doesn’t do anything useful with null, it shouldn’t pretend to do so and rather implement a fail-fast behavior that allows the caller to spot errors as close to the original cause as possible:

public String isSomething(String c) {  
    return c.equals("something")? "YES": "NO";// yes, that ought to fail if c is null
}

If the caller is aware of Optional values and actively using it, there is no need for special support from your side:

Optional<String> o = …;
o = o.map(s -> isSomething(s));
// now o encapsulates "YES", "NO", or is empty

Optional.map does already take care not to evaluate the function if it is empty, hence, your method doesn’t need to accept an optional.


If you have an operation that can truly do something useful if an argument is absent, you should consider the established pattern of method overloading first:

System.out.println("foo"); // prints foo and a newline

System.out.println(); // just prints a newline

here, it is entirely obvious to the reader that omitting the argument is permitted, without ever having to deal with null or Optional.

If you have multiple optional arguments to support, have a look at the Builder Pattern.

Holger
  • 285,553
  • 42
  • 434
  • 765
0

you could write:

public String isSomething(String c) {
    return Optional.ofNullable(c)
            .map(x -> "something".equals(x) ? "YES" : "NO")
            .orElse(null);
}

But whatever you have in place (with slightly modifications) is probably more readable:

public String isSomething(String c) {
    if (c == null) {
        return c;
    }

    return "something".equals(c) ? "YES" : "NO";

}
Flown
  • 11,480
  • 3
  • 45
  • 62
Eugene
  • 117,005
  • 15
  • 201
  • 306