Sunday, September 23, 2012

The evolution of lazy initialization

Lazy initialization is tent pole of Objective C. Apple placed a lot of emphasis on using the pattern in the early iPhone days. That was justified especially considering that the original iPhone shipped with 128MB of RAM, compared to the latest iPhone 5 with 1024MB of RAM.

In the beginning


The ARC evolution


The ARC evolution was fairly tame, allowing us to move the ivar into the implementation files. While the original method was great, and served me well until ARC. With no need to dealloc, and the ability to have iVars that aren't declared in the public interfac.

Clang takes it up a notch


With the most recent versions of Clang you no longer have to use the @synthesize & @dynamic keywords when making @property declarations.
This is all well and good, but I don't want to write my own ivars if I don't have to. So I've set about exploring ways that I can do away with having to create my own ivars.

Option 1.

This approach is comprised of three steps
  1. Public readonly property declaration
  2. Private readwrite property (re)declaration in a class extension
  3. Assign our instance to the ivar

The problem with this is that there is still the ability to overwrite the ivar. Granted it's only from within the class, but still not ideal. This could be an advantage as if you decide to move away from the pattern all you need to do is set the ivar via the mutator.

Option 2.

Another alternative, is to take advantage of another clang feature, where we use the @synthesize directive, to generate a backing ivar on request, without having to explicitly declare the ivar, or at least declare it in a conventional way.
Along with being the smallest version, we can specify the format of our private ivars, so if you want to suffix your underscore rather than prefix it, you have that option.

Whats the solution?

Quite frankly, i don't know. I'm leaning towards Option 2 as it doesn't provide an mutator for the ivar, and so there is almost no suggestion that the ivar should be mutated by anything thing other than the lazy accessor. However I'm interested to hear the opinions of others.

No comments: