Is passing null in to a method acceptable

12,762

Solution 1

It is absolutely fine to pass null to methods. However, if you have a csae where you might not need to pass a variable, consider overloading.

The reason why you might pass a null is because you might have a method with quite a few parameters and you do not wan to implement all possible overloads.

I personally would not use optional parameters - there are many discussions on this very subject because of the issue with the method as Contract which is outside the scope of this question.


UPDATE

Correct way to do it is not to duplicate code but let overloads call each other:

public void Foo(A a)
{
    Foo(a, null);
}
public void Foo(A a, B b)
{
        // .......
}

This will tell client of this code:

  • You can call method with A only
  • You can call method with A and B

If I have only the second method, the client would not know if it is OK to pass null.

Solution 2

I would argue that this is not ok. Passing null around is never a good practice, and in my opinion whenever a value has null it should be an exception. You might not always have control over how your data is passed, and in those cases you should check for null just in case it could occur. However if you have the option to control the arguments yourself, you should rather overload the method, instead of passing in null.

Consider the following scenario:

public string DoSomething(string a, string b)
{
   // Returns something after a and b is processed.
}

In this example we're indicating that a and b are strings. They are objects of type char[] or however you would like to define a string. Passing in a null in this method makes no sense at all, since we're expecting strings. A null is nothing - it's not an empty string - it's simply void.

The reason why I say that I don't think it's preferable to send in null into a method is because there are never any uses for null. It's simply a void left there as a placeholder for something that failed to instansiate. Therefore, calling the method above like this:

DoSomething("whatever", null) makes no sense at all.

We could argue that we could do something like this:

/// <summary>
/// Does something with string a or b
/// </summary>
/// <param name="a">The first string. If it's null, nothing is done with it</param>
/// <param name="b">The second string. If it's null, nothing is done with it</param>
/// <returns></returns>
public string DoSomething(string a, string b)
{
    // Returns something after a and b is processed.
}

But that also makes the code less readable. Why not make an overload DoSomething(string a) ? Or maybe refactor the method completely since it can do something with a and null and still return a valid value. null is not a valid value, so hence the result of an operation including null as an argument should not return a valid value.

It's like using infinity in maths. You will always get infinity as a result if you add/subtract/multiply or divide something with it.

Disclaimer

These are my own opinions, and by no means the 'right' way of programming. But since the question has no right answer, I'll practice my right to free speech :)

Solution 3

That is perfectly acceptable. If you are using C# 4.0 you can also make the parameter optional so that the caller doesn't need to specify the default value.

Solution 4

If you don't use some parameters you can use Overloading or Optional Parameters in C# 4.0

Solution 5

Are you saying "is it ok to pass a null in as a parameter to a method?"

If so - yes - it is perfectly acceptable.

However, in the .Net 4.0 world, you may want to consider using optional parameters so that you don't even need to pass the null in, you can just omit it.

In the pre .Net 4.0 world, if it is a common scenario to pass this null into a method, you may want to create an overload that doesn't take the argument at all.

Share:
12,762
ricki
Author by

ricki

Updated on June 24, 2022

Comments

  • ricki
    ricki about 2 years

    Null is an odd data type for me, it seems as though it is wrong to ever use, maybe its the null pointer errors i got so often as a beginner that now have me associating any instance of null to some kind of evil!

    Anyway my question is

    in some cases is it ok to use null as a parameter? for example, a method may need a and b to do a task, but in some cases it may only need a. Is parsing in null ok for b in those odd instances and checking if(b==null) then we know what called it?

    Or am i way of the mark here?

    i must admit, what got me wondering whether this was acceptable was, the method in question could be overlaoded, but it would have a difference of possibly 5 or 6 lines out of the whole method. This made me worried about code duplication.

  • Rob Levine
    Rob Levine about 13 years
    -1 completely disagree with your first point. If a method isn't meant to allow null, it should do a barrier check and raise an exception (and document it), but the idea that there is something intrinsically wrong with passing a null to a method is nonsense. Whether it is good or bad is completely dependent on the scenario.
  • Yngve B-Nilsen
    Yngve B-Nilsen about 13 years
    @Rob, that's why I'm writing "in my opinion". The question is opinionated, and there is probably no 'correct' answer. I'm updating my answer to further elaborate my view
  • Rob Levine
    Rob Levine about 13 years
    I'm just saying this: how can you have an opinion on whether it is good practice or bad practice without understanding the scenario in which the OP is talking about? Unless you are saying "it is never a good idea" - which sounds a rather dogmatic to me.
  • Paweł Smejda
    Paweł Smejda about 13 years
    @Yngve B. Nilsen There is a lot's of frameworks methods which accept null as parameters without throwing exceptions so I consider this as good practice, depending on scenario as @Rob Levine mentioned
  • Rob Levine
    Rob Levine about 13 years
    However - maybe the -1 was a bit harsh admittedly - I should have just explained what I didn't agree with. I can't remove it now as it is more that 10 mins old, unless you edit the question - then I can take off my -1.
  • ricki
    ricki about 13 years
    thanks for the help, i had never considered chaining calls like that, very good idea and something new to add to my "toolbox" :)
  • Yngve B-Nilsen
    Yngve B-Nilsen about 13 years
    @Rob - no worries :) This question ended up having a lot of nice suggestions. Nothing like a difference of opinion to find the best solution :)
  • Rob Levine
    Rob Levine about 13 years
    @ Yngve - no probs (-1 removed). But let me give a counter example: What about the method SendEmail(string body, string toList, string ccList) - when I have no cc's? I agree that in your specific example it makes no sense - but without understanding the actual specific scenario, your "blanket" rule does seem to much of a blanket.
  • Yngve B-Nilsen
    Yngve B-Nilsen about 13 years
    @Rob - SendEmail should be refactored to take a list of recipients in the ccList instead. the name indicates a List, hence a IList<MailAddress> (or collection) would be a better solution. Then you would pass in an empty List. I'm not saying these 'null'-accepting methods doesn't exist. I really just try to find ways to avoid writing that code myself.
  • Nilzor
    Nilzor about 13 years
    What if CC accepted either 0 or 1 recepients, instead of a list? Would you agree that either a string or null would be acceptable then?
  • Yngve B-Nilsen
    Yngve B-Nilsen about 13 years
    @Nilzor - It all boils down to who's responsible for handeling the arguments. In that case we should move it into an object instead of having all those arguments, and let the object (i.e. MailObject) make sure it's valid. If CC can be null, that's fine and dandy, but we should never have to care.
  • Francis Rodgers
    Francis Rodgers about 11 years
    @Rob - I don't have an opinion either way on the subject although I am inclined to agree with Yngve on his for the most part. As such I also agree it was harsh to give a -1, however, fair play for explaining why you gave it (and for taking it back, although not so much). It really annoys me when people give -1's and don't explain why after taking the time and effort to answer the question. I think requiring an explanation for down voting should be compulsory on SO. Even if you did not take back the down vote, I would still praise you for explaining why you did it. Fair play.