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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With