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.
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;
}
3