Sitemap
Romans Karpelcevs

Romans Karpelcevs

Engineering Manager at Pipedrive

Why lazy-init sucks

2 min readAug 26, 2014

How many times have you created a lazy-init property holding some object that might not be used? Or even an object that’s definitely is going to be used, but it was for some reason more convenient to make lazy?

You’ve just added it in getter, right? So did I. Hundreds of times. And now I’ve come to understand how bad it was. How easy the usage seemed (hey, no need to create anything!) and how ugly the usage becomes in reality. All those _propertyName whenever you’re afraid it’ll be created unexpectedly? Ever caught an object creating instances in dealloc rather than removing? Even if LLDB didn’t, your users most probably did.

Get Romans Karpelcevs’s stories in your inbox

Join Medium for free to get updates from this writer.

No more lazy-init getters. Properties are easy to create. They are, really. Unless you start creating bunch of stuff many times a second, creating them is most probably much faster than creating your “parent” object itself. Especially if it’s a view or a view controller, encapsulating thousands of lines of dependencies in UIKit. Actually, discussing performance when design is at stake is shameful, we all know what’s the root of all evil.

All objects have to be created explicitly. Most probably, in constructor. If you really need that lazy init, do that when starting to use, asking the getter if there’s an object already. People seem to be afraid overriding default constructors of view controllers and putting everything in viewDidLoad:. Bullshit.

Getters must be clean. No, even better. They must be missing in your code completely. Never make an underscore reference from outside the init or init helpers.

How would you be doing that in Swift, anyway?

creative-commons-by-21pxcreative-commons-nc-21pxcreative-commons-sa-21px

--

--