title: How to show if a method may return null
body: <p>After posting <a href="https://stackoverflow.com/questions/410890/how-to-trace-a-nullpointerexception-in-a-chain-of-getters" title="How to trace a NullPointerException in a chain of getters?">this question</a> and reading <a href="https://stackoverflow.com/questions/271526/How-to-avoid-null-statements-in-java" title="how to avoid null statements in java?">that one</a> I realized that it is very important to know if a method is supposed to return null, or if this is considered an error condition and an exceptions should be thrown. There also is a nice discussion when to <a href="https://stackoverflow.com/questions/175532/return-null-or-throw-exception">return ‘null’ or throw exception </a>.</p>
  
  <p><strong>I'm writing a method and I already know if I want to return null or throw an exception, what is the best way to express my decision, in other words, to document my contract?</strong></p>
  
  <p>Some ways I can think of:</p>
  
  <ul>
  <li>Write it down in the specs / the documentation (will anyone read it?)</li>
  <li>Make it part of the method name (as I suggested <a href="https://stackoverflow.com/questions/175532/return-null-or-throw-exception#411400" title="answer on &#39;Return null or throw exception&#39;">here</a>)</li>
  <li>assume that every method that <em>throws</em> an exception will <em>not</em> return null, and every one that does 'not' throw <em>might</em> return null.</li>
  </ul>
  
  <p>I'm mainly talking about java, but it might apply to other languages, too: Why is there a formal way to express if exceptions will be thrown (the <code>throws</code> keywords) but no formal way to express if null might be returned? </p>
  
  <p>Why isn't there something like that:</p>
  
  <pre><code>public notnull Object methodWhichCannotReturnNull(int i) throws Exception
  {
      return null; // this would lead to a compiler error!
  }
  </code></pre>
  
  <h2>Summary and Conclusion</h2>
  
  <p>There are many ways to express the contract:</p>
  
  <ul>
  <li>If your IDE supports it (as IntelliJ), it's best to use an annotation like <code>@NotNull</code> because it is visible to the programmer and can be used for automated compile time checking. There's a <a href="http://groups.csail.mit.edu/pag/jsr308/eclipse/" rel="noreferrer">plugin for Eclipse</a> to add support for these, but it didn't work for me.</li>
  <li>If these are not an option, use custom Types like <code>Option&lt;T&gt;</code> or <code>NotNull&lt;T&gt;</code>, which add clarity and at least runtime checking.</li>
  <li>In any way, documenting the contract in the JavaDoc never hurts and sometimes even helps.</li>
  <li>Using method names to document the <em>nullability</em> of the return value was not proposed by anyone but me, and though it might be very verbose und not always useful, I still believe sometimes it has its advantages, too.</li>
  </ul>