Note that there are some explanatory texts on larger screens.

plurals
  1. POGood or bad practice? Initializing objects in getter
    primarykey
    data
    text
    <p>I have a strange habit it seems... according to my co-worker at least. We've been working on a small project together. The way I wrote the classes is (simplified example):</p> <pre><code>[Serializable()] public class Foo { public Foo() { } private Bar _bar; public Bar Bar { get { if (_bar == null) _bar = new Bar(); return _bar; } set { _bar = value; } } } </code></pre> <p>So, basically, I only initialize any field when a getter is called and the field is still null. I figured this would reduce overload by not initializing any properties that aren't used anywhere.</p> <p>ETA: The reason I did this is that my class has several properties that return an instance of another class, which in turn also have properties with yet more classes, and so on. Calling the constructor for the top class would subsequently call all constructors for all these classes, when they are not <em>always</em> all needed.</p> <p>Are there any objections against this practice, other than personal preference?</p> <p>UPDATE: I have considered the many differing opinions in regards to this question and I will stand by my accepted answer. However, I have now come to a much better understanding of the concept and I'm able to decide when to use it and when not.</p> <p>Cons:</p> <ul> <li>Thread safety issues</li> <li>Not obeying a "setter" request when the value passed is null</li> <li>Micro-optimizations</li> <li>Exception handling should take place in a constructor</li> <li>Need to check for null in class' code</li> </ul> <p>Pros:</p> <ul> <li>Micro-optimizations</li> <li>Properties never return null</li> <li>Delay or avoid loading "heavy" objects</li> </ul> <p>Most of the cons are not applicable to my current library, however I would have to test to see if the "micro-optimizations" are actually optimizing anything at all.</p> <p>LAST UPDATE:</p> <p>Okay, I changed my answer. My original question was whether or not this is a good habit. And I'm now convinced that it's not. Maybe I will still use it in some parts of my current code, but not unconditionally and definitely not all the time. So I'm going to lose my habit and think about it before using it. Thanks everyone!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload