Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check function parameters: Check for null or try/catch

when implementing/using methods that return or work with instances of objects, what is the most elegant approach to check the function parameters ?

Method to call:

someType GetSomething(object x)
{
    if (x == null) {
        return;
    }

    //
    // Code...
    //
}

or better:

someType GetSomething(object x)
{
    if (x == null) {
        throw new ArgumentNullException("x");
    }

    //
    // Code...
    //
}

Calling Method:

void SomeOtherMethod()
{
    someType myType = GetSomething(someObject);

    if (someType == null) {
        return;
    }

}

or better:

void SomeOtherMethod()
{
    try {
        someType myType = GetSomething(someObject);
    } catch (ArgumentNullException) {
    }
}

When browsing through similar questions, the reason not to use try/catch is performance. But IMHO the try-catch just looks better :).

So, which way is more "elegant"?

like image 671
Inno Avatar asked Oct 21 '10 14:10

Inno


3 Answers

If passing in a null is not valid, throw an exception (i.e. - this is an exceptional situation that should never happen).

If a null parameter is valid, return a corresponding object.

In general, accepting null parameters is bad practice - it goes against the principle of least surprise and requires the caller to know it is valid.

like image 155
Oded Avatar answered Nov 04 '22 03:11

Oded


As far as elegance is concerned, it's hard to top Code Contracts.

Contract.Requires(x != null);
like image 44
Austin Salonen Avatar answered Nov 04 '22 01:11

Austin Salonen


You should only use exceptions for exceptional cases. If you expect the argument might be (legitimately) null, you should check it -- do not use exceptions for that. IMO you should check for null at the calling site (before the invocation) if it doesn't make sense to pass null to your method.

like image 35
Kirk Woll Avatar answered Nov 04 '22 01:11

Kirk Woll