Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for Null in Constructor

I'm really trying to figure out the best practices for reusable code that is easily debugged. I have ran into a common practice among developers that I don't quite understand yet.

public MyConstructor(Object myObject)
{
    if (myObject == null)
        throw new ArgumentNullException("myObject is null.");
    _myObject = myObject;
}

It almost seems unnecessary to do this check. But I think it's because I don't completely understand what the benefits of doing this check are. It seems like a null reference exception would be thrown anyway? I am probably wrong, would really like to hear some thoughts on it.

Thank you.

like image 879
jsmith Avatar asked Jan 25 '11 15:01

jsmith


People also ask

How do you check if an object is null?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .

Why is checking for null a good practice?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

IS null check in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator. Let's take an example to understand how we can use the isNull() method or comparison operator for null check of Java object.

Can we return null from constructor?

We can not return any value from constructor... A constructor does not return anything; the "new" operator returns an object that has been initialized using a constructor. If you really want a constructor that may return null, perhaps you should check out the factory method pattern.


2 Answers

To the compiler, null is a legitimate constructor argument.

Your class might be able to handle a null value for myObject. But if it can't - if your class will break when myObject is null - then checking in the constructor allows you to fail fast.

like image 179
Jeff Sternal Avatar answered Sep 20 '22 18:09

Jeff Sternal


Passing a null object is perfectly legal in many cases - for this class the implementor wants to ensure that you cannot create an instance of the class w/o passing a valid Object instance though, so there have to be no checks later on - it's a good practice to ensure this as early as possible, which would be in the constructor.

like image 22
BrokenGlass Avatar answered Sep 17 '22 18:09

BrokenGlass