函数应该返回 null 还是空对象? [英] Should functions return null or an empty object?

查看:36
本文介绍了函数应该返回 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;
}

让我们假设在这个程序中存在有效的情况,即数据库中没有具有该 GUID 的用户信息.我会想象在这种情况下抛出异常是不合适的??此外,我还认为异常处理会影响性能.

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.

此外,如果您尝试访问对象中的成员,返回 null 将导致 null 异常,这对于突出显示错误代码很有用 - 尝试访问没有任何内容的成员是没有意义的.访问空对象的成员不会失败,这意味着错误可以不被发现.

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天全站免登陆