Recently I had a discussion with my teammate on use of Guava
Optional
for optional parameters in a method.
Let's say method is
List<Book> getBooks(String catalogId, Optional<String> categoryId) {
Validate.notNull(catalogId);
Validate.notNull(categoryId); // Point of conflict. Is this required?
which accepts a catalogId
and an optional categoryId
which returns books listed in that catalog and if category is also passed then returns books only in that category.
Point of conflict was, Validating Optional<String> categoryId
for null check. I was of view point that there should not be a null check on it since it's an optional parameter. Caller of the function can either pass null
or Optional.<String>absent()
and getBooks
function should handle both cases by doing if(categoryId==null && categoryId.isPresent())
in the implementation.
My opinion was that Optional
for optional parameters just makes the contract of the method more clear. One can tell just by looking at method signature that this parameter is optional and does not need to read the javadocs. But he should not be forced to pass Optional.absent()
when he does not want to use that optional parameter.
My team mate had different view. He wanted to put a null check for it and hence force the caller to always pass Optional.<String>absent()
. His point was that why would we pass a null optional. Moreover getBooks("catalog123", Optional.absent())
looks more readable than getBooks("catalog123", null)
.
This method is in one of our library packages and is used by multiple packages owned by us.
What are your suggestions on usage of Optional
for this scenario?
Thanks