commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Sean C. Sullivan" <>
Subject Re: [httpclient] question regarding HttpMethod interface: getResponseBody method
Date Sun, 10 Feb 2002 22:03:57 GMT

From: "dIon Gillard" <>

> Sean C. Sullivan wrote:
> >Currently, (an interface) defines a
> >method called "getResponseBody":
> >
> >    /**
> >     * Return my response body, if any,
> >     * as a byte array.
> >     * Otherwise return <tt>null</tt>.
> >     */
> >    public byte[] getResponseBody();
> >
> >
> >I would prefer if this method returns a  zero-length array instead
> >of null.
> >
> >Returning a zero-length array is one of the API design tips that
> >is recommended in Josh Bloch's book:
> >
> >       Effective Java Programming Language Guide
> >
> >
> >
> >==> Item 27: Return zero-length arrays, not nulls
> >
> given I don't have the book handy, this doesn't make for a very
> convincing argument as to why we should change the API. [...]
> Can you please provide some more info on why you'd like the change?

First, I want the behavior of getResponseBody to be consistent with
the behavior of other "standard" (java.*) classes.

Example 1:  java.util.Vector.toArray

  The return value, Object[], will never be null.

Example 2: java.lang.String.getBytes

  The return value, byte[], will never be null.

In Josh Bloch's book, "Effective Java Programming Language Guide",
Item 27 states:

        Return zero-length arrays, not nulls


If the method sometimes returns null and other times returns a non-null array,
the programmer is forced to always check for null.

With the current HttpMethod interface, programmers must write:

  byte[] result = hm.getResponseBody();
  if (result != null)

If we return a zero-length array instead of null, programmers can write:

   byte[] result = hm.getResponseBody();

> As well, the  current api documents returning null. Which is cheaper from the
> perspective than creating a new byte array.

Bloch (page 134) writes:

 "It is sometimes argued that a null return value is preferable to a
  array because it avoids the expense of allocating the array. This argument
  on two counts. First, it is inadvisable to worry about performance at this
  unless profiling has shown that the method in question is a real contributor
  performance problems. Second, it is possible to return the same zero-length
  array from every invocation that returns no items because zero-length arrays
  are immutable and immutable objects may be shared freely."

Solution:  declare a static zero-length array variable

  private final static byte[] ZERO_LENGTH_BYTE_ARRAY = new byte[0];



To unsubscribe, e-mail:   <>
For additional commands, e-mail: <>

View raw message