Home >Java >javaTutorial >Item - Return empty collections or arrays rather than null

Item - Return empty collections or arrays rather than null

DDD
DDDOriginal
2024-09-13 06:19:06632browse

Item - Retorne coleções ou arrays vazios, em vez de nulos

Do not return null:

  • Methods that return null in place of empty collections or arrays require additional client handling to avoid exceptions.

Problems with null:

  • Clients need to add redundant checks (if to check for null).
  • Omissions in these checks may go unnoticed, resulting in bugs.
  • It makes it difficult to implement the method that returns the collection or array.

Argument against null:

  • Don't worry about the performance of allocating empty collections or arrays unless it is proven to be a bottleneck.

Efficient alternatives:

  • Use empty collections or arrays instead of null.
  • Immutable collections can be returned repeatedly (e.g.: Collections.emptyList(), Collections.emptySet()).
  • Empty arrays can also be returned efficiently.

Optimized performance:

  • Use reusable empty immutable collections to avoid unnecessary new allocations.
  • Return the same empty array instead of creating a new one each time

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn