DEV Community

Discussion on: Lazy props for the lazy!

Collapse
fluffynuts profile image
Davyd McColl Author

I've always been wary of Lazy -- and I have a good example of why:

Lazy will capture whatever is in the given func which resulted in this oddness during testing:

A colleague had a Lazy prop which pulled information out of application config (ConfigurationManager). The testing environment sets up temporary redis and mysql databases (actually spins up new instances of the processes) and rewrites the app config with the applicable ports to connect on. ConfigurationManager is quite aggressive with caching, so in order to get updated config in the rest of your application, you have to do something like:

var config = 
  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Redis.Port"].Value = 
  _tempRedis.Port.ToString();
config.Save(ConfigurationSaveMode.Modified);

And the consuming code elsewhere has to read the config after you've done this.

The problem we saw was that a lazy prop which was using this config never gets the updated value, because the app config was captured too early (and this test setup code runs far before any test code, so I'm not entirely sure exactly when it's done). We had to work around this capturing behavior.

In addition, there's no way to reset a Lazy -- and sometimes you really need to. Consider where you might have a lazy prop exposing the total value of a shopping card. When the customer adds a new item, the underlying field can just be set to null and the next time someone wants a total, they can just read from the property.

I don't see any huge advantage over a regular old lazy prop (it's not significantly less code). If Lazy is working ok for you, then cool (: I have just been bitten a few times by it not being as lazy as it says it is :D

Anyways, thanks for reading & thanks for commenting! Discussion is always good!