William
William

Reputation: 55

Writing Javadoc for return-type 'Optional<T>'

I'm currently writing a Java-API for SOAP-webservices used at my workplace.
The webservice-classes are generated with Axis2 and they can return null. As I don't want to deal with null-references on my business logic level, I'm using Optional<> as return-type.
For example:

/**
 * Reads account-data to given accountId. 
 * 
 * @param accountId
 *          the primary key of table 'account'
 * @return  the account wrapped as an Optional<>, if an account with primary key 'accountId' exists; Optional.empty(), else
 */
public Optional<Account> readAccount(long accountId) throws RemoteException, ServiceFaultException {
        // prepare SOAP-Request
        ReadAccount request = new ReadAccount();
        request.setAccountId(accountId);

        // execute SOAP-Request
        ReadAccountResponse response = accountService.readAccount(request);

        // process Response
        Optional<Account> account = Optional.ofNullable(response.getAccount());

        return account;
    }

The above method executes a webservice-operation to search for some account-record in a database. If there is no account to be found with matching argument accountId, the method call response.getAccount() can return null.

Is there a more concise way of writing the Javadoc for @return?
Especially for the phrase "wrapped as an Optional<>"?

(I know that the answers might be opinion based, but I haven't found any recommendations for this on stackoverflow or by googling.)

Upvotes: 5

Views: 3976

Answers (2)

Eugene
Eugene

Reputation: 120988

Why not say it how the jdk does? For example Stream::reduce:

@return an {@link Optional} describing the result of the reduction

In your case it would be:

an Optional describing the account.

Upvotes: 3

Austin Schaefer
Austin Schaefer

Reputation: 696

I would suggest simplying your return statement javadoc to the following:

/**
 * Reads account-data to given accountId. 
 * 
 * @param accountId
 *          the primary key of table 'account'
 * @return the account wrapped in an {@link Optional}
 */
public Optional<Account> readAccount(long accountId) throws RemoteException, ServiceFaultException {
  // function here
}

the reason for this is because Optional.empty() is an expected and unchanging part of the Optional API; every developer who knows what an Optional is will know to expect an empty Optional if the account is missing; and will understand he needs to access the actual information inside the Optional if the account is present.

We provide a @link here to allow developers who haven't heard of Optionals to look up its respective javadoc and understand how it works; this is itself not mandatory, but can be helpful if there are a lot of less experienced developers working on your project.

Upvotes: 2

Related Questions