从函数返回数据的最佳实践是什么?是返回Null对象好还是返回空对象好?为什么要选择一种而不是另一种呢?

考虑一下:

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的用户信息。我认为在这种情况下抛出异常是不合适的??另外,我的印象是异常处理会损害性能。


当前回答

有趣的问题,我认为没有“正确”的答案,因为它总是取决于你的代码的职责。您的方法是否知道没有找到的数据是否存在问题?在大多数情况下,答案是“不”,这就是为什么返回null并让调用者处理他的情况是完美的。

也许区分抛出方法和返回null方法的一个好方法是在您的团队中找到一个约定:如果没有得到任何东西,表示它们“得到”某些东西的方法应该抛出异常。可能返回null的方法可以以不同的方式命名,可能是“Find…”。

其他回答

如果返回的对象是可以迭代的对象,我将返回一个空对象,这样我就不必首先测试null。

例子:

bool IsAdministrator(User user)
{
    var groupsOfUser = GetGroupsOfUser(user);

    // This foreach would cause a run time exception if groupsOfUser is null.
    foreach (var groupOfUser in groupsOfUser) 
    {
        if (groupOfUser.Name == "Administrators")
        {
            return true;
        }
    }

    return false;
}

我们使用CSLA。NET,并且它认为失败的数据获取应该返回一个“空”对象。这实际上是相当烦人的,因为它要求检查obj。IsNew而不是obj == null。

正如前面提到的,null返回值将导致代码立即失败,从而降低了由空对象引起的隐形问题的可能性。

就我个人而言,我认为null更优雅。

这是一种非常常见的情况,我很惊讶这里的人似乎对此感到惊讶:在任何web应用程序中,数据通常是使用querystring参数获取的,这显然会被破坏,因此要求开发人员处理“未找到”的情况。

你可以这样处理:

if (User.Exists(id)) {
  this.User = User.Fetch(id);
} else {
  Response.Redirect("~/notfound.aspx");
}

...但是这每次都是对数据库的额外调用,这在高流量页面上可能是一个问题。而:

this.User = User.Fetch(id);

if (this.User == null) {
  Response.Redirect("~/notfound.aspx");
}

...只需要一个呼叫。

You should be throwing an exception if it is an exceptional circumstance that you call that code with an invalid user ID. If it is NOT an exceptional circumstance, then what you are essentially doing is using a "getter" method to test whether a user exists or not. That is like trying to open a file to see if it exists or not (lets stick to c#/java here) instead of using the exists method, or trying to access dictionary elements and seeing if they exist by looking at the return value instead of using the "contains" method first.

因此,您很可能会使用诸如“exists”之类的额外方法来首先检查是否存在这样的用户。异常的性能绝对不是完全不使用它们的理由,除非您有真正的性能问题。

在这种情况下,如果没有这样的用户,则最好返回“null”。还要使你的方法是静态的。

编辑:

通常这样的方法是一些“User”类的成员,不能访问它的实例成员。在这种情况下,方法应该是静态的,否则你必须创建一个“User”的实例,然后调用GetUserById方法,该方法将返回另一个“User”实例。我同意这很令人困惑。但是如果GetUserById方法是某个“DatabaseFactory”类的成员,那么将它作为实例成员是没有问题的。

这是一个业务问题,取决于具有特定Guid Id的用户的存在是否是该函数的预期正常用例,还是会阻止应用程序成功完成该方法向用户对象提供的任何功能的异常情况……

如果它是一个“异常”,因为缺少具有该Id的用户将阻止应用程序成功完成它正在做的任何功能,(假设我们正在为我们已向其发货的客户创建发票……),那么这种情况应该抛出ArgumentException(或其他一些自定义异常)。

如果没有用户(调用此函数的潜在正常结果之一),则返回空值....

编辑:(处理亚当在另一个回答中的评论)

If the application contains multiple business processes, one or more of which require a User in order to complete successfully, and one or more of which can complete successfully without a user, then the exception should be thrown further up the call stack, closer to where the business processes which require a User are calling this thread of execution. Methods between this method and that point (where the exception is being thrown) should just communicate that no user exists (null, boolean, whatever - this is an implementation detail).

但是如果应用程序中的所有进程都需要一个用户,我仍然会在这个方法中抛出异常……