Do not return null:
Problems with null:
Argument against null:
Efficient alternatives:
Optimized performance:
Code examples:
Incorrect method that returns null:
// Exemplo incorreto public ListgetCheeses() { return cheesesInStock.isEmpty() ? null : new ArrayList(cheesesInStock); }
Inadequate customer treatment:
Listcheeses = 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 ListgetCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList(cheesesInStock); }
Using an immutable empty collection:
public ListgetCheeses() { 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3