BIT-101 [2003-2017]

Dot Notation or Square Brackets?


In Objective-C, you call methods with square brackets. Instead of:

[c]myObject.myMethod();[/c]

it’s:

[c][myObject myMethod];[/c]

Instead of:

[c]myObject.myMethod(argument);[/c]

it’s:

[c][myObject myMethod:argument];[/c]

Bizarre at first to many, but it really does grow on you. Especially with multiple arguments, it’s like having named parameters. Compare code that looks like this:

[c]myObject.setProperties(100, 100, 50, 50);[/c]

to this:

[c][myObject setPropertyX:100 y:100 width:100 height:100];[/c]

A contrived example, but you see how you always know what the parameters are.

Now, you can also set up getters and setters, by creating a private instance variable, and then either writing your own getters and setters or using @property and @synthesize (or a combination of both techniques).

In Objective-C, the getter name is the same as the private variable name, and the setter is “set” + the var name with initial cap. i.e. for variable, “stuff”, you’d have public methods, “stuff” and “setStuff”. So you can do stuff like:

[c]int i = [myObject stuff];[/c]

and:

[c][myOtherObject setStuff:i];[/c]

But, at this point, you can now shortcut that with dot notation, which is much more familiar to many coming from other languages:

[c]int i = myObject.stuff;
myOtherObject.stuff = i;[/c]

At first, I was all over dot notation because I’m used to it. But as time goes on, I find myself seeing it as ugly. Mostly out of a respect for consistency. You wind up with stuff like this:

[c][myObject doSomething];
myObject.x = 15;
[myObject doSomethingElse:@“abc”];
myObject.b = YES;[/c]

It starts to feel like you are coding in two different languages. So I’ve been making an effort to use only brackets. It’s a bit more verbose, but looks a lot cleaner:

[c][myObject doSomething];
[myObject setX:15];
[myObject doSomethingElse:@“abc”];
[myObject setB:YES];[/c]

There’s one use case that bugs me though: += (and its kin). With dot notation, you’re fine:

[c]myObject.x += 10;[/c]

But you can’t really do that with bracket notation. You wind up with:

[c][myObject setX:[myObject x] + 15];[/c]

Which just takes me back to Flash 4’s getProperty/setProperty. Remember moving a movie clip around with:

[as]setProperty(myMC, “_x”, getProperty(myMC, “_x”) + 1);[/as]

Ugh. Thought I had escaped stuff like that. 🙂

Anyway, for now, I’m going on a purist kick and avoiding dot notation altogether. I may drop back and be pragmatic about it after a while.

« Previous Post
Next Post »