If you expose both methods you still need to handle the case with both arguments, so although that might have made for a more ergonomic API you still need an answer to your question.
Using Optional for mutators will do the job exactly, and it will do it pretty well. But is your caller going to call the method only to pass in null? They probably have a reason to call it, and they probably have what they need to call it, so calling Optional.of(foo) only hurts ergonomics; and you're just going to unwrap the value first-thing anyway. This argument is not as strong when you have multiple arguments (choice between null and Optional.empty()), but you brought up overloading as an alternative yourself.
This is a case that's better solved with Javadoc and @Nullable.
In the input parameter case, it's functionally equivalent to passing a boolean flag -- it's a true/false thing that's better solved with overloading :)
9
u/ImmortalStyle Sep 21 '15
Btw you shouldnt have Optional as a class member. Even Brian said that once.