Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I've been heavily using a pattern for years now, but I don't know what it's called.

It looks like this....

class xzy
{

  public function getFoo()
  {
    if ( undefined(this.foo) )
    {
       this.foo = new Foo;
    }
    return this.foo
  }

  public function setFoo(foo)
  {
    this.foo = foo;
    return this;
  }

  public function getResult()
  {
    if ( undefined(this.result) )
    {
       this.result = this.getFoo().action();
    }
    return this.result;
  }

}

It find it great for testing yet still allows for a high level of encapsulation. It's also great for drying up code. I also very rarely use a constructor. I'm now in a position where I could really do with specifying the pattern in some documentation but I don't know what it's called and it's a hard thing to try and Google.

share|improve this question

1 Answer 1

up vote 9 down vote accepted

lazy initialization

I like to use it to cache a calculation result that is expensive and it allows me to clear the cache easily when one of the variables change (and when there are likely more changes waiting to happen):

public Rectangle getBoundingRect(){
    if(bbox==null){
    bbox=calculateBBox();
    }
    return bbox;
}

private Rectangle calculateBBox(){
    //expensive operation
    return //...
}

public void updateGeom(){
    bbox=null;
}
share|improve this answer
    
Thank you. I was thinking it was lazy loading, so I wasn't a million miles off. I also use it to DRY up code. I'm in love with it but it's causing me problems when I have to collaborate with other people. I get some weird looks. –  tomwrong Sep 10 '13 at 13:24
1  
+1 Also known as lazy instantiation –  Marjan Venema Sep 10 '13 at 13:54
1  
@tomwrong If there's data access, you can call it lazy loading. I'd call it lazy loading in conversation anyway ... fewer syllables :) –  svidgen Sep 10 '13 at 15:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.