0

Recently I've adopted a handy way to make sure tree-like structure members are aware of their parent node:

private metaCollection<metaPage> _servicePages;
/// <summary>
/// Registry of service pages used by this document
/// </summary>
[Category("metaDocument")]
[DisplayName("servicePages")]
[Description("Registry of service pages used by this document")]
public metaCollection<metaPage> servicePages
{
    get
        {
        if (_servicePages == null) {
            _servicePages = new metaCollection<metaPage>();
            _servicePages.parent = this;
        }
        return _servicePages;
    }
}

(the concept is to create instance for private field within property get method)

I would love to know if this pattern has some common-known name? and even more: are there known issues / bad implications on such practice?

Thanks!

hardyVeles
  • 1,112
  • 11
  • 13
  • 3
    Somewhat relevant to your question (note the part about "lazy initialization"): https://softwareengineering.stackexchange.com/questions/82377/should-properties-have-side-effects – hatchet - done with SOverflow May 08 '17 at 21:37
  • 1
    I can feel your excitement, but no, there is no common-known name for this, nor is it a pattern, because you see a) it is not in widespread use, b) only you know about it, and c) it is rather trivial. – Mike Nakis May 08 '17 at 21:39
  • 1
    I'm confused with your notion "only you know about it" - to me seems impossible no one faced tree consistency issue and solved it like this. In other hand, if it is true you say no one use this / it-s not widespread - than I'm even more worried about potential problems might later come. – hardyVeles May 08 '17 at 22:01
  • 2
    Sometimes this is quite useful, especially in a `set` accessor where you want to percolate changes down to select leaves. Just watch out for concurrency issues. – Aluan Haddad May 09 '17 at 00:09

1 Answers1

1

Yes, it's called Lazy Initialization. From the example on the Wikipedia Lazy Loading page:

Lazy initialization

Main article: Lazy initialization

With lazy initialization, the object to be lazily loaded is originally set to null, and every request for the object checks for null and creates it "on the fly" before returning it first, as in this C# example:

private int myWidgetID;
private Widget myWidget = null;

public Widget MyWidget 
{
    get 
    {
        if (myWidget == null) 
        {
            myWidget = Widget.Load(myWidgetID);
        }    

        return myWidget;
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43