Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid passing a reference to a parent object when constructing a new instance of a class?

I have two classes defined as follows.

First one:

internal class Content {

   internal Content(Master master) {
        // code omitted
   }

// code omitted
}

second one:

public class Master {

     internal Content content { get; set; }

     internal Master() {
         // code omitted
     }

// code omitted
}

Exposing the Content Class as property of the Master I need to do something like this:

Master M = new Master(); 
M.content = new Content(M); 

Is there a way to do not pass the Master (M) in the Content Consctructor?

like image 549
User907863 Avatar asked Feb 20 '23 18:02

User907863


2 Answers

Presumably Content needs a Master ? Actually, constructors are a fairly good way of managing this, but if that is a problem, you could also do something like:

internal class Content {
    internal void SetMaster(Master master) {this.master = master; }
    //...
}
internal class Master {
    internal void SetContent(Content content) {
        if(content == null) throw new ArgumentNullException("content");
        // maybe handle double-calls...
        this.content = content;
        content.SetMaster(this);
    }
}
...
Master M = new Master();
M.SetContent(new Content());

or have Master create the Content by default. Frankly, though, I'd leave it "as is" until there is an actual "this is a problem".

like image 91
Marc Gravell Avatar answered Feb 22 '23 07:02

Marc Gravell


Why not use lazy initialisation idom?

public class Master
{
    private Content _content;

    internal Content content
    {
        get
        {
            if (_content == null)
            {
                _content = new Content(this);
            }
            return _content;
        }
    }
}

If Master always has to have content property set then create Content member during construction:

public class Master
{
    internal Content content
    {
        get; private set;
    }

    internal Master()
    {
        content = new Content(this);
    }
}

You may also use mixed approach:

public class Master
{
    internal Content content
    {
        get; private set;
    }

    internal Content GetOrCreateContent()
    {
        if (content == null)
        {
            content = new Content(this);
        }
        return content;
    }

    internal Master()
    {
    }
}
like image 22
gwiazdorrr Avatar answered Feb 22 '23 08:02

gwiazdorrr