好记性不如铅笔头

effective java, java, 编程

《Effective Java》读书笔记:不要返回NULL

最近在看《 Effective Java 》这本书,里面提到了编码时需要注意【 不要返回NULL(Rule439) 】,这里备份下实现的注意点,截图版权属于原作者。

github:

【 https://github.com/cstriker1407/think_in_java 】

下面备份下返回数组和返回List等方法:

class Rule43Bean
{
	//sth
}
class NullClass
{
	private static final Rule43Bean[] emptyArray = new Rule43Bean[0];
	private List<Rule43Bean> list = new ArrayList<Rule43Bean>();
	
	/*some methods*/
	
	//返回数组
	public Rule43Bean[] getArrs()
	{
		return list.toArray(emptyArray);
	}
	
	//返回list
	public List<Rule43Bean> getList()
	{
		if (list.isEmpty())
		{//返回空的list
			return Collections.emptyList();
		}else
		{//保护性拷贝
			return new ArrayList<Rule43Bean>(list);
		}
	}
}

 原书介绍:

发表评论

1 × 3 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据