Search code examples
nullpointerexceptionjavadoc

JavaDoc warn of possible NullPointerException


I've written a method that returns the most likely LAN Interface on Android. Since the user may not be connected to a LAN, it's possible for this method to return null. How should I warn callers about this possibility in the JavaDoc? I don't think I should use @throws since the method doesn't actually throw a NullPointerException.


Solution

  • I think the right way to do this would be in the return clause:

    /**
     * ...
     * @return {@code null} if the user is not connected to a LAN, else the most
     * likely LAN interface.
     */
    public LanInterface getMostLikelyInterface();
    

    It would be the responsibility of the caller to know that this means not to use the returned value before a check.

    Though you could use Guavas' Optional class instead:

    /**
     * ...
     * @return Optional.absent if the user is not connected to a Lan interface,
     *    else the most likely one.
     */
    public Optional<LanInterface> getMostLikelyInterface();
    

    The users then would have to use if(iface.isPresent()), which is much more readable than if(iface != null).