Alex Rivera | Logout

Sending reference of object before its construction

Asked 2012-08-02T20:00:34.300
64

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?

Edit
Report

1 Answer

17

If you encounter this pattern, you might check if it can be refactored into this instead:

public class First()
{
      private Second _second;

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

      private class Second
      {
          public Second(First f)
          {
          }
      }
}

Passing the dependency into the constructor implies a kind of tight coupling between the two classes, as First has to trust that Second knows what it is doing and won't try to rely on the uninitialized state of First. This kind of strong coupling is more appropriate when Second is a private nested subclass (and hence a clear implementation detail) or possibly when it's an internal class.

answered 2012-08-02T20:09:24.167

Your Answer