如果函数返回null或一个空对象? [英] Should functions return null or an empty object?

查看:238
本文介绍了如果函数返回null或一个空对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是的从函数返回数据时,最好的做法的。它是更好地返回null或一个空对象?为什么人应该做一个比其他?

What is the best practice when returning data from functions. Is it better to return a Null or an empty object? And why should one do one over the other?

考虑一下:

public UserEntity GetUserById(Guid userId)
{
     //Imagine some code here to access database.....

     //Check if data was returned and return a null if none found
     if (!DataExists)
        return null; 
        //Should I be doing this here instead? 
        //return new UserEntity();  
     else
        return existingUserEntity;
}

让pretend会有有效的情况下,这一计划将有与该GUID数据库中没有用户信息。我猜想,这是不恰当扔在这种情况下,一个异常?另外,我的IM pression异常处理下会损害性能。

Lets pretend that there would be valid cases in this program that there would be no user information in the database with that GUID. I Would imagine that it would not be appropriate to throw an exception in this case?? Also I am under the impression that exception handling can hurt performance.

推荐答案

返回null通常是最好的主意,如果你打算表示没有数据可用。

Returning null is usually the best idea if you intend to indicate that no data is available.

这是空对象意味着数据已经返回,而返回null清楚地表明,什么也没有回来。

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

此外,返回一个空将导致空异常,如果您尝试访问成员中的对象,这对于突出越野车code有用的 - 试图访问的任何一个成员是没有意义的。会员访问一个空的对象不会失败意味着错误可以去发现。

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

这篇关于如果函数返回null或一个空对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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