I few days ago my colleague Arthur Shagall reviewing my code suggested me to use Lazy Object pattern to postpone some calculations during the load time. I hadn’t heard about the pattern before and even googling it didn’t give my much information. So I have decided to write this article to cover the topic.
Lazy Object allows you to postpone some calculation until the moment when the actual result of the calculation is used. That may help you to speed up booting of the application.
It is pretty simple. We create a proxy object that takes a calculation block as its property and execute it on first method call.
1 2 3 4 5 6 7 8 9 10 11 12 13
Usage example 1
A constant assignment like this:
Could be converted to this one:
So now if you want to use
SQUARES it still behaves like an array:
1 2 3
Usage example 2
Let’s say you have models
Address in you Rails application.
What you want do is to validate inclusion of
address.state in states.
You can just hardcore the list of states:
1 2 3 4 5
But it does not reflect your changes in DB in any way.
Then you can fetch the values from DB:
It seems to look better, but there are 2 possible pitfalls:
- It increases load time (1 more SQL query)
- It may cause real troubles if
STATESis initialized before
Statemodel is seeded. In this case
STATESwill be empty.
So that is the situation where Lazy Object is useful:
If your prefer to have it as a ruby gem, please take a look at rubygems.org/gems/lazy_object.
Thanks for reading!