什么是最好的实践情况下,一个参数为空? [英] What is the best practice in case one argument is null?

查看:256
本文介绍了什么是最好的实践情况下,一个参数为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在验证方法的输入,我用来检查参数为空,如果是这样我抛出一个ArgumentNullException。我这样做是为每列表中的每个参数,所以我结束了code是这样的:

when validating methods' input, I used to check if the argument is null, and if so I throw an ArgumentNullException. I do this for each and every argument in the list so I end up with code like this:

 public User CreateUser(string userName, string password, 
                            string Email, string emailAlerts, 
                            string channelDescription)
    {

        if (string.IsNullOrEmpty(userName))
            throw new ArgumentNullException("Username can't be null");

        if (string.IsNullOrEmpty(Email))
            throw new ArgumentNullException("Email can't be null");
       //etc, etc, etc
    }

这样行吗?我为什么要这么做?难道是确定的,如果我只是集团所有的检查,并返回一个空值,而不是抛出的异常?什么是解决这一问题的最佳做法是什么?

PS:我要改变这一点,因为长的方法,它会非常繁琐这样做。
想法?

Is this OK? Why should I do this? Would it be ok if I simply group all the checks and return a null value instead of throwing the exception? What is the best practice to address this situation?

PS: I want to change this, because with long methods, it gets very tedious to do so.
Ideas?

推荐答案

请一个ArgChecker类像这样

Make an ArgChecker class with something like this

  ArgChecker.ThrowOnStringNullOrEmpty(userName, "Username");

其中,ThrowOnStringNullOrEmpty为

where ThrowOnStringNullOrEmpty is

  public static void ThrowOnStringNullOrEmpty(string arg, string name)
  {
      if (string.IsNullOrEmpty(arg))
        throw new ArgumentNullException(name + " can't be null");
  }

您也可以尝试来处理使用PARAMS阿根廷,就像参数列表:

You could also try to process a list of arguments using a params arg, like:

  public static void ThrowOnAnyStringNullOrEmpty(params string[] argAndNames)
  {
       for (int i = 0; i < argAndName.Length; i+=2) {
          ThrowOnStringNullOrEmpty(argAndNames[i], argAndNames[i+1]);
       }
  }

和调用像这样

  ArgChecker.ThrowOnAnyStringNullOrEmpty(userName, "Username", Email, "email");

这篇关于什么是最好的实践情况下,一个参数为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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