Immutable objects
Avoid null if possible
Output parameters:
null
, since the object needs to be created by the callerString
, for example,
cannot be used as an output parameter, since it cannot change stateHere, 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", request, idValue) ) { * //use aIdValue * } * </pre> * * @param cookieName the non-null name attached to the Cookie. * @param request is the non-null request forwarded from the user's browser which * is to be examined for the presence of the given cookie. * @param cookieValue 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 cookieName, HttpServletRequest request, final StringBuilder cookieValue ){ if (cookieValue.length()>0) throw new IllegalArgumentException(); boolean userHasCookie = false; Cookie[] cookies = request.getCookies(); if (cookies != null){ for(Cookie cookie : cookies){ if (cookieName.equals(cookie.getName())){ userHasCookie = true; //change the state of the output param (aCookieValue) cookieValue.append(cookie.getValue()); } } } return userHasCookie; } }
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.