繁体   English   中英

我应该返回-1还是int? 或使用out参数返回数据库操作的结果?

[英]Should I return -1 or int? or use out parameter to return result of a database action?

我在一个项目中编写一些打算从其他项目中调用的数据库操作的公共函数。 直接编写代码,我可以采用以下方法:

public int GetCount(Apple apple, Orange orange)
{
    try 
    { 
       // query; 

       return 1000;
    } 
    catch 
    { 
        // log it
        return -1; 
    }
}

要么

public int? GetCount(Apple apple, Orange orange)
{
    try 
    { 
       // query; 

       return 1000;
    } 
    catch 
    { 
        // log it
        return null; 
    }
}

要么

public bool GetCount(Apple apple, Orange orange, out int count)
{
    count = -1;
    try 
    { 
       // query; 

       count = 1000;
       return true;
    } 
    catch 
    { 
        // log it
        return false; 
    }
}

我目前对其他业务对象执行“空”方式,例如:

public Apple GetApple(Orange orange)
{
    try 
    { 
       // query; 

       return apple;
    } 
    catch 
    { 
        // log it
        return null; 
    }
}

然后,调用者检查返回的值是否为null并因此弹出一条错误消息。 所以我倾向于使用int? 作为值类型的返回类型。 但是我很想知道什么是可接受的设计或鼓励实践。

编辑:如果我把try catch放在调用者周围,那会不会让我的代码库到处都是try catch? 从被调用方捕获异常不是更容易,这样调用它的所有函数都不需要关心吗? 如果被呼叫者捕获到错误并让呼叫者知道发生了一些错误,那怎么办?

吞下异常是不好的做法。

如果该方法无法处理该异常,则将其冒泡给调用方:

public int GetCount(Apple apple, Orange orange)
{
    try 
    { 
       // query; 

       return 1000;
    } 
    catch 
    { 
        // log it
        throw;
    }
}

好吧,这是相当主观的,您不会得到标准化的答案,但是《 框架设计指南》一书是开发约定的好资源,它指出:“不要通过捕获非特定的异常(例如ExceptionSystemException吞并错误”。 如果吞下它并返回一些魔法值,包括null ,那么您将无法识别系统故障的根本原因。

就个人而言,我会

public int GetCount(Apple apple, Orange orange)
{
    try 
    { 
       return // query; 
    } 
    catch 
    { 
        // log it
        throw;
    }
}

另一个个人观点-我花了太多时间进行诊断和调试,以了解系统为何无法正常运行,然后,最后,只是发现该异常已被静默记录并吞下了。 现在,当遇到诸如catch(Exception e) { return null; }这样的代码时,我感到非常痛苦catch(Exception e) { return null; } catch(Exception e) { return null; }

int提供的值对于域显然不合法的情况下,并且不需要default<int>为零以外的任何default<int> ,我看不到Nullable<T>任何好处。 Nullable<int>类型使调用者无法使用,因为必须先测试null值,然后在使用前将值提取到其他存储位置。 如果有人犯了以下错误:

if (res.HasValue)
  for (i=0; i<res.Value; i++)
    ....

那么循环开销将是原来的两倍以上:

if (res.HasValue)
{
  int resValue = res.Value;
  for (i=0; i<resValue; i++)
    ....
}

但是要求调用者创建一个额外的变量来避免不必要的循环开销,这似乎很麻烦。

我会用int? 也一样 重要的是要注意,这可以帮助您使用所有数字-而不保留特定的数字来标识状态。

这就是CC++缺少的,它们使用整数来传达状态,而无意间保留了一个数字以供特殊用途。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM