4

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.

10

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;
}
  • 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. – thomas-peter 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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