Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why check if a class variable is null before instantiating a new object in the constructor?

With a previous team I worked with, whenever a new Service class was created to handle business logic between the data layer and presentation layer, something like the following was done:

class DocumentService
{
    public DocumentRepository DocumentRepository { get; set; }

    public DocumentService()
    {
         if (DocumentRepository == null) DocumentRepository = new DocumentRepository();
    }
}

I never quite understood why the check for null was there. If the constructor is being called, that means it HAS to be null..since it's a new instance, right?

Why would this be done? It seems to me like it is a redundant step, but I don't want to miss anything and pass it off as bad practice.

like image 369
Cody Avatar asked May 22 '13 13:05

Cody


People also ask

When creating a new object for a class what is used to initialize the object?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.

What is the keyword used to instantiate create an object in Java?

Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

What is instantiation of class in Java?

Instantiate in Java means to call a constructor of a Class which creates an an instance or object, of the type of that Class. Instantiation allocates the initial memory for the object and returns a reference.


1 Answers

In this exact context: Yes it is redundant.

There is no immediate reason for this code, it could be a left-over from an older method or anticipating on an implementation with multiple constructors. But I would not recommend using this 'pattern' or even keeping this code.

like image 94
Henk Holterman Avatar answered Oct 05 '22 18:10

Henk Holterman