title: Guava Optional as method argument for optional parameters
body: <p>Recently I had a discussion with my teammate on use of <code>Guava</code> <code>Optional</code> for optional parameters in a method. </p>
  
  <p>Let's say method is</p>
  
  <pre><code>List&lt;Book&gt; getBooks(String catalogId, Optional&lt;String&gt; categoryId) {
       Validate.notNull(catalogId);
       Validate.notNull(categoryId); // Point of conflict. Is this required?
  </code></pre>
  
  <p>which accepts a <code>catalogId</code> and an <strong>optional</strong> <code>categoryId</code> which returns books listed in that catalog and if category is also passed then returns books only in that category.</p>
  
  <p>Point of conflict was, Validating <code>Optional&lt;String&gt; categoryId</code> 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 <code>null</code> or <code>Optional.&lt;String&gt;absent()</code> and <code>getBooks</code> function should handle both cases by doing <code>if(categoryId==null &amp;&amp; categoryId.isPresent())</code> in the implementation.</p>
  
  <p>My opinion was that <code>Optional</code> 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 <code>Optional.absent()</code> when he does not want to use that optional parameter.</p>
  
  <p>My team mate had different view. He wanted to put a null check for it and hence force the caller to always pass <code>Optional.&lt;String&gt;absent()</code>. His point was that why would we pass a null optional. Moreover <code>getBooks("catalog123", Optional.absent())</code> looks more readable than <code>getBooks("catalog123", null)</code>.</p>
  
  <p>This method is in one of our library packages and is used by multiple packages owned by us.</p>
  
  <p>What are your suggestions on usage of <code>Optional</code> for this scenario? </p>
  
  <p>Thanks</p>