Using Optional as a Method Argument in Java – Pros and Cons

functional programmingjavajava8

With Java 8, I've seen more and more articles about the use of Option/Optional. I understand what they trying to represent, and I see many examples of them being used as returns. However what I don't see is them being used as method/function arguments in languages that don't have the syntax for default/optional parameters.

Is there any reason not to use Optional as a method argument in the case where you know the argument is something that may or may not be needed? Here's an example I could think of:

Optional<Customer> lookupCustomer(String firstName, Optional<String> middleName, String lastName)

Best Answer

One reason is that conceptually, firstName, middleName, and lastName are logically one argument, not three. They're all parts of a bigger whole, and one can imagine that they're almost always passed together. In functional languages they'd likely be passed as a tuple or record; Java lacks those, so they'd probably be aggregated into a Name class. Note that if you needed to compose functions that take and return full names, you wouldn't be able to without aggregating them - you can only return one value, after all.

Maybe it just doesn't come up very often that a value is optional and also not part of a bigger whole. If the function requires a certain value to do its work, then that function shouldn't be accepting an Optional. If you need to chain operations that might not return a value, aborting with Nothing if any function along the way fails, you can chain calls to flatMap, and if you want to fail with an exception you can use get() at any step of the way or at the end of the chain.

If a value is truly optional and a function does two different things based on its presence or absence, that's a code smell unless the function is a wrapper of two smaller functions that do one thing each, and that particular combination of decisions is very common.

I don't think it's so much that it's wrong as it is a relatively uncommon use case.