Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending reference of object before its construction

I have seen the following code in one of our applications:

public class First() {       private Second _second;        public First()       {           _second = new Second(this);           // Doing some other initialization stuff,       }  }  public class Second {     public Second(First f)     {     } } 

In the First() constructor, isn't it bad that we are sending a reference of class First() before it is fully constructed? I am thinking that the object is only fully constructed once the control logic leaves the constructor.

Or is this okay?

like image 674
user1202434 Avatar asked Aug 02 '12 20:08

user1202434


People also ask

Can we pass this in constructor?

this() can be used to invoke current class constructor. this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this can be used to return the current class instance from the method.

Can we pass this in constructor in Java?

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.

What is creating an instance of a class?

Note: The phrase "instantiating a class" means the same thing as "creating an 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.


1 Answers

My question is, in the First() constructor, isnt it bad that we are sending a reference of class First() BEFORE it is fully constructed?

Somewhat. It can be a problem, certainly.

If the Second constructor just holds onto a reference for later use, that's not too bad. If, on the other hand, the Second constructor calls back into First:

public Second(First f) {     f.DoSomethingUsingState(); } 

... and the state hasn't been set up yet, then that would of course be a Very Bad Thing. If you call a virtual method on First then it could be even worse - you could end up calling into some code which hasn't even had a chance to run any of its constructor body yet (although its variable initializers will have been executed).

In particular, readonly fields may be seen first with one value and then later with another...

I blogged about this a while ago, which may provide some more information.

Of course, without doing this sort of thing, it's pretty hard to create two mutually-referential immutable objects...

like image 176
Jon Skeet Avatar answered Sep 28 '22 02:09

Jon Skeet