zoukankan      html  css  js  c++  java
  • Effective Java 43 Return empty arrays or collections, not nulls

    Feature

    Return empty arrays or collection

    Return nulls

    Avoids the expense of allocating the array

    N

    Y

    Return value is immutable which may be shared freely

    Y

    N

       

    Standard idiom for dumping items from a collection into a typed array

       

    public class Shop {

    // The right way to return an array from a collection

    private final List<Cheese> cheesesInStock = new ArrayList<Cheese>();

       

    // This prevent allocating an new Array every time which handles the expense issue.

    private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

       

    /**

    * @return an array containing all of the cheeses in the shop.

    */

    public Cheese[] getCheeses() {

    return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);

    }

       

    public static void main(String[] args) {

    Shop shop = new Shop();

    // User don't have to check the null of the returned array since it always returns an empty array

    if (Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON))

    System.out.println("Jolly good, just the thing.");

    }

    }

       

       

    A collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection.

    /**

    * The right way to return a copy of a collection

    * @return an array containing all of the cheeses in the shop.

    */

    public List<Cheese> getCheeseList() {

    if (cheesesInStock.isEmpty())

    return Collections.emptyList(); // Always returns same list

    else

    return new ArrayList<Cheese>(cheesesInStock); // This is defensive copy to avoid the mutable object to be modified by the client.

    }

       

    Summary

    There is no reason ever to return null from an array or collection-valued method instead of returning an empty array or collection.

  • 相关阅读:
    redis简单使用及连接池
    初始Redis
    redis安装教程
    .whel文件的打开方式
    xpath选择器的使用,selenium使用
    爬虫之bs4的使用,之爬取汽车之家新闻,之代理池的搭建
    爬虫基础 之 爬取梨视频 模拟登陆 爬取妹子图
    git基本使用

    re模块正则表达式
  • 原文地址:https://www.cnblogs.com/haokaibo/p/return-empty-arrays-or-collections-not-nulls.html
Copyright © 2011-2022 走看看