JavaRush /Java Blog /Random EN /Return a zero-length array, not null
alexnjc
Level 31

Return a zero-length array, not null

Published in the Random EN group
Often there are methods that look like this:
private List cheesesInStock =;
/**
* @return массив, содержащий все сыры, имеющиеся в магазине,
* or null, если сыров для продажи нет.
*/
public Cheese[] getCheeses() {
if (cheesesInStock.size() == 0)
return null;
}
There is no reason to treat as a special case a situation where there is no cheese on sale. This requires the client to write additional code to process the method's return value пull, for example:
Cheese[] cheeses = shop.getCheeses();
if (cheeses ! = пull &&
Аrrауs.аsList(shор.gеtСhееsеs()).соntаins(Сhееsе.SТILТON))
Sуstеm.оut.рrintln("Jоllу good, just the thing.");
instead of simple:
if  (Аrrаys.аsList(shор.gеtСhееsеs()).соntаins(Сhееsе.SТILTON)) Sуstеm.оut.рrintln("Jоllу good, just the thing.");
This kind of verbosity is necessary for almost every method call that returns null instead of a zero-length array. This is fraught with errors, since the client developer may not have written special code to process the result null. The error may go undetected for years because such methods typically return one or more objects. It should also be mentioned that returning nullinstead of an array leads to complication of the method itself that returns the array. It is sometimes argued that returning null is preferable to returning a zero-length array because it avoids the expense of allocating the array in memory. This argument fails for two reasons. First, there is no point in worrying about performance at this level unless profiling of the program shows that this particular method is the main reason for the performance degradation. Second, each call to a method that does not return records can pass the same zero-length array to the client, because any zero-length array is immutable, and immutable objects can be shared. In fact, this is exactly what happens when you use the standard idiom for dumping elements from a collection into a type-controlled array:
private List сhееsеsInStосk =,
private fiпаl static Cheese[] NULL_CHEESE_ARRAY = nеw Cheese[0];
 /**
* @геtuгп массие, содержащий все сыры, имеющиеся в магазине
*/
public Cheese[] getCheeses() {
геtuгп (Cheese[] сhееsеsInStосk.tоАггау(NULL_СНЕЕSЕ_АRRАУ);
}
In this idiom, a constant, as a zero-length array,toArray is passed to a method to indicate what type it should return. Typically, the method toArrayallocates memory space for the returned array, but if the collection is empty, it is placed in the input array, and the specification Сollесtion,tоАггау(Оbjесt[])ensures that if the input array is large enough to contain the collection, that is what is returned. Therefore, the presented idiom will never itself allocate a zero-length array into memory, but uses a “type-specific constant” as such. Let's summarize. There is no reason for an array method to return null rather than a zero-length array. This idiom appears to stem from the C programming language, where the length of an array is returned separately from the array itself. In C, it is useless to allocate memory for a zero-length array. Source: Joshua Bloch, Java TM Effective Programming, Lori Publishing House
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION