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:
- must be visible in both a method and its caller
- cannot be null, since the object needs to be created by the caller
- cannot be immutable objects - a String, for example, cannot be used as an output parameter, since it cannot change state
- should probably be used only occasionally, and after careful consideration
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 :
Would you use this technique?