Religious Obj-C Programmers


Referring to the section in the Chapter on the ‘self’ variable…

“For example, many Objective-C programmers are quite religious about accessor methods; they never read or write to an instance variable except using its accessor methods”.

Then the reader is asked to revise the bodyMassIndex method to ‘please those purists’.

I don’t understand the advantage or appeal of writing the bodyMassIndex implementation that way (i.e. with the ‘self’ variables).

Seems like extra code.

What’s gained?


Future proofing. If someone needs to change how a member is handled in the future, it’s a safer change if all code, even the class itself, uses accessor methods. If no one uses the member directly, you can even remove it freely, so long as you leave the accessor methods in place.


I’m not sure I follow. Could I bother you for an example?


Here’s an example: Let’s say you wanted to be able to ask a Person what there age is. In version 1 of your program, you declare an instance variable and a method for reading it:

[code]@interface Person : NSObject
int age;

  • (int)age;

Then in version 2, you realize that the person’s age keeps increasing, so you change the implementation to store their dateOfBirth and calculate the age from that:

[code]@interface Person : NSObject
NSDate *dateOfBirth;

  • (int)age;

In Person.m, anywhere that you used the method age, everything still works.

But! Anywhere that you accessed the age instance variable directly is broken, because the instance variable is gone.


I follow that, but I don’t see how the ‘self’ variable fixes that problem.

I need to do some more thinking on that.


If you are using the age method, it looks like this:

int ageInOneHundredYears = [self age] + 100;
If you are using the age variable directly, it looks like this:

So, you need self in order to call the method.


It may help to illustrate the situation if you modify the age method to return a different value. Or, you may simply write a log statement into the age method and if you call age with self you will see that log statement appear; if you call it without, you will not.


OK, I think I see now. Thanks!