You are currently looking at an older section of the wincent.com website.
Please check the new version of the site at https://wincent.com/ for updated content.

wincent Wincent Colaiuta's weblog

« Whittling away the controller | Main | Category bonanza »

July 14, 2005

The best way to write accessors

As you learn Objective-C you'll come across lots of advice about how, when and why to write accessor methods and you'll see many, many different ways of writing them.

The answer to the "when" question is easy, especially now that we have Accessorizer: Always. Always write accessors. In the old days writing accessors was time consuming and even if you wanted to come up with a set of preprocessor macros to use as shortcuts it still made sense to be selective about when you wrote accessors. Now it's just too easy: select a slab of instance variables and let Accessorizer do the work.

The answer to the "why" question is simple: Just trust me. Seeing as writing accessors is easy, just take my word for it and go about your business; sooner or later you'll find yourself in a situation where you'll have a revelation. You'll say to yourself, "Wow, that refactoring I just did was so easy because I had those accessor methods; would've been hell without it", or, "Man, I'm glad I had those threadsafe accessor methods; it's made it so easy to start using these classes without having to think too much about threadsafety issues", or, "Gee, those accessor methods have sure made it easy to throw stuff around in my Model-View-Controller object diagram", and so forth. Once you've had a few of these experiences you'll never question the "why" of writing accessors again.

The "how" question is the most difficult. Once I'd learned the Cocoa memory management paradigm I still found myself asking, "So what's the best way to write an accessor?". I wanted to get past the 5, 10 or 15 different ways I'd seen of writing accessors to the one, best way of writing them.

There are lots of articles on how to write accessors and I won't rehash them here (examples: here, here, here and here), but the key lesson is there is no single best way to write accessors. Hmmm. Perhaps I can phrase that more positively: instead of searching for the holy grail of accessors, always choose the right accessor for the job.

Things to bear in mind when choosing an accessor for "the job":

More Cocoa articles , More Development articles

Posted by wincent at July 14, 2005 11:01 AM