Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to check if an object is null or not?

Tags:

.net

null

Where do you check if an object that you are passing to a method is null or not?

Should an object need to be tested before calling a method? or within the method that is using the argument?

public class Program
{
    public static void Main(string[] args)
    {
        // Check if person is null here? or within PrintAge?

        PrintAge(new Person { Age = 1 });
    }

    private static void PrintAge(Person person)
    {
        // check if person is null here?

        Console.WriteLine("Age = {0}", person.Age);
    }
}

public class Person
{
    public int Age { get; set; }
}

Having a "null" check in both classes seem to be too much redundant code.

[EDIT]: What would be an dis/advantage of checking for null within a caller or a callee?

[EDIT2]: I just ran into Defensive Programming and it seems like it advocates checking null within a callee. I wonder if this is a widely accepted practice.

like image 803
dance2die Avatar asked Apr 01 '09 16:04

dance2die


People also ask

How do you check if it is null in Java?

To check if a string is null or empty in Java, use the == operator.

How do you check if an object is null in JS?

JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.

How do you check if something is null in Python?

Use the is operator to check if a variable is null in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None . Copied! Note that there isn't a null value in Python.

When an object is null in Java?

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).


3 Answers

If you design a library, there will be methods exposed to the outer world. You should check the incoming data in this methods. No checks are required in methods that you do not expose, because only your code calls them and its logic should handle all cases you accepted in the exposed method called.

                    --------------------------
                   |                          |
                   |         Library          |
                   |                          |
 -------        ---------        ----------   |
|       |      |         |      |          |  |
| Outer |      | Library |      | Library  |  |
|       | ===> | Entry   | ===> | Backend/ |  |
| World |      | Method  |      | Helpers  |  |
|       |      |         |      |          |  |
 -------        ---------        ----------   |
                   |                          |
                   |                          |
                    --------------------------

If you have accepted the supplied data in the entry method, you should perform the requested action and return the expected result, that is handle all remaining cases.

UPDATE

To clarify the situation inside the library. There might be null checks, but only because of the logic, not because of parameter validation. There are two possibilities for the location of null checks inside the library. The first one if the called method knows how to handle null values.

private CallingMethod()
{
   CalledMethod(someData);
}

private CalledMethod(Object parameter)
{
   if (parameter == null)
   {
      // Do something
   }
   else
   {
      // Do something else
   }
}

And the second situation if you call a method that cannot handle null values.

private CallingMethod()
{
   if (someData == null)
   {
      // Do the work myself or call another method
   }
   else
   {
      CalledMethod(someData);
   }
}

private CalledMethod(Object parameter)
{
   // Do something
}

The whole idea is to reject cases you cannot handle immediately and handle all remaining cases properly. If the input is not valid you throw an exception. This forces the library caller to supply only valid values and does not allow the caller to continue execution with meaningless return values (besides the caller shallows the exception an continues).

like image 66
Daniel Brückner Avatar answered Oct 18 '22 23:10

Daniel Brückner


You've got nothing to check in Main - you're using the new operator which never returns null (except for Nullable<T>).

It would be entirely reasonable to check in PrintAge, particularly if it were made public. (For private APIs it's less important to do argument checking, but it can still be very useful.)

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

These days in C# 3.0 I usually use an extension method for this.

like image 6
Jon Skeet Avatar answered Oct 18 '22 23:10

Jon Skeet


You can design a method to work with valid objects only.

That means you are expect to receive valid objects ( not null in your case ).
That means you don't know how to react and what to do with invalid objects:

  • returning silently from the function is not a solution;
  • throwing an exception will mean you move responsibility to the upper methods where they can check the value already before passing to you.

So if your method don't know exactly how to handle invalid object and the method won't follow additional logic in the invalid case you should put

Debug.Assert( Person );

at the PrintAge begin and this will force you to make checks upper by call stack.

The lower function in hierarchy is the less checks it should do. The following is disadvantages of doing checks in the functions that do the work.

  • Function that is doing actual work has to be as clear as possible without mass of ifs
  • Function will be called more then many times
  • Such function can call such functions and they can call such functions again. Each of them will perform the same validation
like image 4
Mykola Golubyev Avatar answered Oct 18 '22 22:10

Mykola Golubyev