什么是检查方法的参数的最佳方法? [英] What is the best way to check the parameters of the method?

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

问题描述

我知道两种方法来检查方法的参数,并在需要时抛出异常。



1)检查各一个参数,并抛出一个异常时,这是错误的

 公共无效方法(对象参数1,对象参数2)
{
如果(参数1 == NULL )
{
抛出新的ArgumentNullException(参数1);
}

如果(参数2 == NULL)
{
抛出新的ArgumentNullException(参数2);
}


}



2)检查所有参数一次,并抛出同样的异常所有:

 公共无效方法(对象参数1,对象参数2)
{
如果(参数1 == NULL ||参数2 == NULL)
{
抛出新的ArgumentNullException();
}


}



第一种方法是,在我看来,更好,更洁净,还翻唱了很多线路。例如,实际进行2行代码的方法 - 在这种方式的代码将通过4行(包括空行)每个参数增加



我对在是有经验的程序员使用的方法。是否有比这两个更好的办法?


解决方案

如果您使用的是.NET Framework 4中,检查出的代码契约中,从而简化下来的代码



<$ p单行$ p> 公共字符串反转(字符串文本)
{
Contract.Requires< ArgumentNullException>(!文本= NULL,参数不能为空);

.....
}



原因你会使用,这是因为你现在可自动如 Pex公司工具来告诉你哪些应用单元测试于该方法。它也给你在编译时反馈,如果这个方法会根据你如何调用它抛出一个异常。像

 字符串文本= NULL; 
字符串reversedString =反向(文字);



编译器会提醒你,这将引发异常。



请注意代码契约需要安装的加载项,但它是免费的。


I know two ways to check parameters of the method and throw exceptions when it is needed.

1) Check one each parameter and throw an exception when it is wrong:

public void Method(object parameter1, object parameter2)
{
    if (parameter1 == null)
    {
        throw new ArgumentNullException("parameter1");
    }

    if (parameter2 == null)
    {
        throw new ArgumentNullException("parameter2");
    }

    ...
}

2) Check all parameters at once and throw same exception for all:

public void Method(object parameter1, object parameter2)
{
    if (parameter1 == null || parameter2 == null)
    {
        throw new ArgumentNullException();
    }

    ...
}

The first approach is, in my opinion, better and cleaner, but also cover a lot of lines. For example, a method that actually do the 2 lines of code - in this way code will increase by 4 rows (including blank line) for each parameter.

I am interested in is the approach used by experienced programmers. Are there better ways than these two?

解决方案

If you are using .NET framework 4, check out Code Contracts, which simplifies it down to a single line of code

public string Reverse(string text)
{
   Contract.Requires<ArgumentNullException>(text!=null, "ParAmeter cannot be null.");

   .....
}

The reason you would use this is because you can now get automated tools like Pex to tell you what unit tests to apply to this method. It also gives you feedback at compile time if this method would throw an exception based on how you are calling it. Like

String text = null;
String reversedString = Reverse(text);

The compiler will warn you that this will throw an exception.

Note Code Contracts needs an add-in to be installed, but it is free.

这篇关于什么是检查方法的参数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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