Home >Java >javaTutorial >Item - Return empty collections or arrays rather than null
Do not return null:
Problems with null:
Argument against null:
Efficient alternatives:
Optimized performance:
Code examples:
Incorrect method that returns null:
// Exemplo incorreto public List<Cheese> getCheeses() { return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock); }
Inadequate customer treatment:
List<Cheese> cheeses = shop.getCheeses(); if (cheeses != null && !cheeses.isEmpty()) { // Lógica para lidar com queijos disponíveis }
Correct method that returns an empty collection:
// Exemplo correto public List<Cheese> getCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList<>(cheesesInStock); }
Using an immutable empty collection:
public List<Cheese> getCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList<>(cheesesInStock); }
Use with empty arrays:
// Retorno de array vazio corretamente public Cheese[] getCheeses() { return cheesesInStock.toArray(new Cheese[0]); }
Optimized use of empty array:
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0]; public Cheese[] getCheeses() { return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY); }
Conclusion:
Never return null: Always prefer empty collections or arrays. This simplifies the API, prevents errors, and rarely negatively impacts performance.
The above is the detailed content of Item - Return empty collections or arrays rather than null. For more information, please follow other related articles on the PHP Chinese website!