One of the reasons for not using an Optional<T>
as an input parameter is that you will likely have to construct it on-the-fly just to pass it to that method.
Even if now you have an Optional<Book>
ready to use, from findBook
, it may be that future changes to the code will mean the Optional
is unwrapped and you end up with a naked Book
you'll have to wrap. That would be annoying, at least.
The solution with unwrapping the Optional
when calling the doSomething
method is, I think, the best quick fix available.
Ideally, you want to avoid situations like this from occuring, as they cause confusion and could lead to bugs.
Depending on the semantics, the complexity of your doSomething
and the importance of the Book
parameter you could:
Create a doSomething(Book book, SomeOtherSutff someOtherStuff)
and a doSomething(SomeOtherSutff someOtherStuff)
. This is useful if doSomething
can be called standalone, without a Book
, from other parts of the code.
Split doSomething
in three: before doing Book
things, doing Book
things and "the rest of the processing". This can have various benefits, especially when processing many items. It may be that instead of doing (A, B, C), (A, B, C), ..., (A, B, C)
that it's better to do (A, A, ..., A), (B, B, ..., B), (C, C, ...C)
or (A, A, ..., A), (B, C), (B, C), ..., (B, C)
Do nothing. It doesn't seem like more than a minor annoyance and making changes will cost time and risk introducing bugs.