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

Return an array of zero length, 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 the situation where there is no cheese on sale. This requires the client to write additional code to handle the method's return value пull, such as:
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 needed almost every time a method is called that returns null instead of a zero-length array. This is error-prone, as the client developer might not have written special code to handle the result null. The bug can go unnoticed for years because such methods typically return one or more objects. It should also be mentioned that the returnnullinstead of an array leads to the complication of the method itself, which returns an array. It is sometimes argued that returning null is preferable to returning a zero-length array because it avoids the overhead of allocating the array in memory. This argument is invalid for two reasons. First, there is no point in worrying about performance at this level, unless profiling the program shows that this method is the main cause of performance degradation. Second, every time a method is called that returns no records, the same zero-length array can be passed to the client, because any zero-length array is immutable, and immutable objects are shared. Actually, that's exactly what's happening
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 zero-length array constant is passed to the method toArrayto indicate what type it should return. Normally, the method toArrayallocates memory space for the returned array, however, if the collection is empty, it is placed in the input array, and the specificationСollесtion,tоАггау(Оbjесt[])guarantees that if the input' array is large enough to contain the collection, it will be returned. Therefore, the presented idiom will never itself allocate a zero-length array in memory, but uses a "constant with type indication" as such. Let's summarize. There is no reason for an array method to return null rather than a zero-length array. This idiom seems 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 Efficient Programming, Lori Publishing
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION