Output parameters

A method may occasionally need to use a parameter for its return value - what might be loosely called an "output parameter" or a "result parameter". The caller creates an output parameter object, and then passes it to a method which changes the state of the object (its data). When the method returns, the caller then examines this new state.

Output parameters:

Example

Here, there's both an output parameter (aCookieValue) and a boolean return value: if the output parameter is indeed populated, then the return value is set to true.


import javax.servlet.http.*;

public final class CookieValue {

   /**
   * Determine if a user's request contains a particular cookie, and if it does
   * then place its value in an "out" parameter.
   *
   * Example
   * <pre>
   * if ( CookieValue.getCookieValue("ID", aRequest, aIdValue) ) {
   *   //use aIdValue
   * }
   * </pre>
   *
   * @param aCookieName the non-null name attached to the Cookie.
   * @param aRequest is the non-null request forwarded from the user's browser which
   * is to be examined for the presence of the given cookie.
   * @param aCookieValue is a non-null "out" parameter in which the
   * cookie's value is placed - if found - for further examination by the
   * caller; it must have a zero length.
   * @throws IllegalArgumentException if aCookieValue.length() > 0.
   */
   static boolean getCookieValue(
     String aCookieName, HttpServletRequest aRequest, final StringBuilder aCookieValue
   ){
      if (aCookieValue.length()>0) throw new IllegalArgumentException();
      boolean userHasCookie = false;
      Cookie[] cookies = aRequest.getCookies();
      if (cookies != null){
        for(Cookie cookie : cookies){
          if (aCookieName.equals(cookie.getName())){          
            userHasCookie = true;
            //change the state of the output param (aCookieValue)
            aCookieValue.append(cookie.getValue());
          }
        }
      }
      return userHasCookie;
   }
} 


An alternative design is to return a null value if the cookie is not actually present. This would replace the current boolean return value with a String return value which should be checked for null. However, that alternative design seems weaker, since it seems prudent to avoid using null return values.

See Also :
Immutable objects
Avoid null if possible
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -