返回NULL的替代方法 [英] Alternatives to returning NULL

查看:209
本文介绍了返回NULL的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   /**
     * Returns the foo with the matching id in this list
     * 
     * @param id the id of the foo to return
     * @return the foo with the matching id in this list
     */
    public Foo getFoo(int id)
    {
        for (Foo foo : list)
        {
            if (foo.getID() == id)
            {
                return foo;
            }
        }

        return null;
    }

而不是返回 null 当没有找到 foo 时,我应该 throw 一个异常?是否有关于这个问题的最佳实践成语?顺便说一句,我知道我的例子有点设计,但我希望你得到这个想法...

Instead of returning null when foo is not found, should I throw an exception? Does it matter, and is there a "best practices" idiom on the subject? By the way, I know my example is a bit contrived, but I hope you get the idea...

谢谢。

编辑

根据更改代码以获取 Foo > id ,以更好地说明现实世界的情况。

Changed code to get Foo based on id to better illustrate a real-world scenario.

推荐答案

返回 null 不仅处理更简单,效果更好。必须使用例外处理例外案例。

Returning null is not only more simple to handle, performs better too. The exceptions must be used to handle exceptional cases.

这篇关于返回NULL的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆