What is the best way to check the parameters of the method?

☆樱花仙子☆ 提交于 2019-12-21 09:15:46

问题


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?


回答1:


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.




回答2:


Use method attribute to cleanly check your parameters. i was wrote a framework for parameter validating in python.the c# best practice is here




回答3:


Approach 1 is significantly more useful in my opinion. NullReferenceExceptions, or in this case ArgumentNullExceptions thrown where you can't determine what was null is very frustrating.

Also, if you don't like looking at the validation code you can always wrap it in a code region and fold it away in your IDE.




回答4:


i know it's an old thread but i'd like to share MHO. this is what i normally do:

create a generic method:

private void ValidateArgument<exType>(Func<bool> validation, string errorMessage) where exType : Exception
        {
            if (validation())
            {
                throw Activator.CreateInstance(typeof(exType), errorMessage) as exType;
            }
        }

and then from the calling method you do:

this.ValidateArgument<ArgumentException>(() => string.IsNullOrEmpty(firstname), "firstname must be supplied");



回答5:


Personally I usually use methods that check or validate code and return false when they fail (and perhaps log/display an error).

I like to check all issues and validate them all, so using || would basically stop at the first test.




回答6:


Either approach is fine. Basically throwing an ArgumentNullException is the right thing to do here.

as the documentation for it says

the exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.




回答7:


It depends on what is actually required.

  1. If you need to throw different exceptions for both null values, then you should go for first approach.

  2. If both null cases are just the same for your code, then second approach would be better readable.



来源:https://stackoverflow.com/questions/9954506/what-is-the-best-way-to-check-the-parameters-of-the-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!