Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"Lazy" is used in two different contexts.</p> <p>The first, when critiquing a class design, argues that a class is ineffectual -- that it doesn't do enough to justify its existence. People also call this kind of class "thin." <strong>This is probably not what you mean here.</strong></p> <p>Second, <strong>lazy evaluation</strong> and <strong>lazy instantiation</strong> mean that the class only does the work of evaluating a property or initializing itself when actually needed.</p> <p>For example, suppose we have a class that makes an Employee object.</p> <pre><code> @implementation Employee - (id) initWithID: (IdentificationCode*) ident { self =[super init] if (self) { _records=[self retrieveEmployeeRecordsFor: ident]; _identification=ident; } return self; } </code></pre> <p>This is fine, but retrieving all the records from a database might be slow. And sometimes we don't need to do the work. For example:</p> <pre><code>- (BOOL) isFounder { if (indent.number&lt;10) return YES; return NO; } </code></pre> <p>If we're instantiating an Employee simply to find out if they're a Founder, we don't need to look up their records at all! </p> <pre><code> ..... if ([thisEmployee isFounder]) { [self sendCandyTo: thisEmployee.identification]; } </code></pre> <p>On the other hand, sometimes we need them:</p> <pre><code>- (NSArray*) payments { return [self.records retrievePayStubs]; } </code></pre> <p>So, if we're constructing an Employee just to call <code>isFounder</code>, we waste a database lookup. But we can't just skip that, because <code>payments</code> needs it. </p> <p>What we do is take the database lookup out of the constructor and put it in a <code>load</code> method.</p> <pre><code>- (void) load { if (records) return; self.records=[self retrieveEmployeeRecordsFor: ident]; } - (NSArray*) payments { [self load]; return [self.records retrievePayStubs]; } </code></pre> <p>Now, we only load the employee records when we actually need them. If they've already been loaded, we don't do any extra work (aside from one method call). If we never need the payment records, then we don't need to do the work at all. </p> <p>The class only works when it has to -- and waits 'til the last minute to do the work. It's "lazy!"</p>
 

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