Question

I have a question about the best coding practice for lazy instantiation. 

I have a custom class (MainClass) that consitutes the model of my view controller. One of the properties of MainClass is another custom class (SubClass). Now let's say I want to acces and set some of the properties of SubClass from my view controller. Should I lazy instantiate SubClass in MainClass?

Lazy instantiating SubClass in MainClass save me the trouble to check the existence of SubClass (and to create it if it doesn't exist) every time I want to set one of its properties.

On the other hand though I lose the ability to set variables in my views only if SubClass exists. Let me explain better. Let's say I want to set the stringValue of my textfield only if SubClass.name exists. Every time I ask for the existence of SubClass.name the MainClass will lazily instantiate SubClass which is a waste.

What's the best way to proceed?

Was it helpful?

Solution

You need to make up your mind about the aesthetics, if that's what's driving this question, or you need to explain the performance constraints.

Yes, lazy initialization has advantages and disadvantages.

ADVANTAGES

  • you don't pay for objects you never use
  • you don't need actually set fields on the object you won't ever use
  • if you need it, you can build the object at the last minute, which is usually preferable to building it at startup

DISADVANTAGES

  • (slight) complexity -- especially if you or colleagues aren't accustomed to the idiom
  • if you forget to call Initialize() or equivalent in an accessor, you may get tricky bugs in some languages, or crashes in others

A hybrid approach is possible. For important tasks, use lazy instantiation:

 - (void) display {
     [self initialize];
     [self display];
     }

and for unimportant tasks, simply check for initialization.

 - (void) updateCaches {
     if ([self isInitialized]) {
         [self reloadCachedDataFrom: [self startDatabaseSession]];
     }
 }

You don't want to build your object just to update its caches, but perhaps, if the object is live, you would like to go ahead and keep the caches warm. So, you see if you've already instantiated the object, and reload the caches only if it already has been set up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top