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.