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.

This entry was posted in Objective C. Bookmark the permalink.

18 Responses to Dot Notation or Square Brackets?

  1. kp says:

    Also, in making my own classes, I’ll often throw in an “add to” function or similar that takes care of that, so I can say:

    [myObject addToX:15];

  2. Marcus Geduld says:

    I’m fascinated by how difficult it is for many people to switch from myObject.method() to [myObject method]. I’m surprised by people’s resistance to something that’s a minor typographical difference. It’s not a paradigm shift, like moving from imperative to functional programming.

    And I’ve seen it crop up in many circumstances, in myself and others. For instance, people who switch from a C-family language to Python take a surprisingly long time to feel comfortable with the lack of semicolons.

    I’m not belittling people. I have trouble with this stuff myself. It just surprises me. I would predict people would have an easier time with what is, essentially, a straight-forward substitution. But the mind clearly sees these “surface” features as more profound than I would guess.

    I recently tried to learn Inform7, a language for creating text-adventure games. It’s fascinating to study if you’re an experienced programmer, because it’s syntax is close to English.

    The code looks like this:

    To the west of the dungeon is a forest. Inside the forest there are trees. Trees are climbable.

    Of course, this syntax in meant to make Inform7 easy for non-coders. But I found it really, really difficult. I kept trying to mentally translate the English-like syntax into something like Actionscript.

    (I’ve also had a harder time than I thought I would mastering the mxml shorthands for Actionscipt constructs, and it really bugs me when I don’t instantly get what the mxml is doing, in AS terms.)

    I’m also embarrassed (but I’d wager not alone) to admit that I sometimes have trouble parsing the order of variable-name/type in different languages. If I’m reading a Java book because there’s no AS book about the subject that happens to interest me, I sometimes get tripped up by “int varName” as opposed to “varName : int”. The mental hiccup only lasts a second, but it’s jarring.

    My mind seems to take “little” matters like punctuation and word order very seriously. I suspect that once it learns the rules in a specific language, it relaxes and goes into a sort of auto-pilot. Learning the syntax of a new language is like going from driving in America to driving in England. The left/right-side-of-the-road shift is simultaneously trivial and profound.

  3. Tomas says:

    Perl is a favorite in syntax and flexibility ๐Ÿ™‚

    function(param1 => 100, param2 => 50, list => [ @array, ‘extra’ ], %extra_params);

  4. Erik says:

    Note that even the G-borg’s official Obj-C coding standards forbids dot notation access of properties: http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml#Properties

  5. anton says:

    Thanks Keith. This sort of simple, “Rosetta Stone” -like direct explanation is the kind of thing I’ve been pining for since I began attempting to wrap my brain around Obj-C. While it may seem elementary, more of this will always be welcome!

  6. MattLloyd says:

    This might be a very contrived example but I’ve recently found using the @public modifier for variables and using myClass->myVar useful instead of the . accessor. I’ve never been a fan of using properties when a public variable will suffice.

  7. It does look cleaner, but I still like my dot notation. Like you said though, it’s probably just because I’m so used to it.

    Also have to make a quick comment about this bit:
    setProperty(myMC, “_x”, getProperty(myMC, “_x”) + 1);

    ugh! I got to that part and a strange chill went up my side… and then I threw up a little in my mouth…

  8. kp says:

    Jason, yes, we all love our dots, but I’m all or nothing on it. Hate the mix worse than anything.

    Erik, thanks for the reference. I feel vindicated. ๐Ÿ™‚

  9. Mr Speaker says:

    Excellent post! Thank you… I was having some difficulties figuring out when and why you should use each notation – this has cleared it up: it’s arbitrary! woot! I had an issue with the square brackets not (as Marcus Geduld suggests) because of a minor typographical change, but because it’s inconsistent in all the code examples I see! It makes it more like learning a real language than a programming language where you have to learn the rules and exceptions at the same time ๐Ÿ˜‰

  10. kp says:

    Mr. Speaker, glad you got something out of it. Yep, it is pretty arbitrary. The google style guide mentioned above gives some pretty good reasons NOT to use dot notation though. I’m sure some will disagree, but that’s cool.

  11. Tim says:

    Thanks for the post. I decided to take a look around and see what other experienced Obj-C programmers think of this. From what I could gather, the general consensus for most developers ( except some of those coming from AS or .NET ) was to avoid the dot notation as much as possible. Then I stumbled on a post that makes allot of sense: http://eschatologist.net/blog/?p=160 – When to use properties & dot notation. It speaks of separation of state and behavior. After reading that, I think i might consider using dot syntax for things like value objects. Its great to have super clean looking code. However, maybe utilizing a language feature, such as the dot notation, in a manner of distinction might help towards that goal. Maybe not. By the way, wasn’t it possible before the dot notation came along (2.0) to us the -> to access objects in the same manner? Now that’s really ugly. As much as I like a language like php, I’m super glad we don’t have to see dollar signs and arrows everywhere! The brackets do grow on you… (and you don’t have to hold the shift key down to type them like you do the constant parentheses of other languages).

  12. Justin says:

    @Markus
    Indeed, our brains seem to correlate syntax or look with function and behavior more than we think. There’s a game you can play with physics (or any science) students where you give them flashcards of common formulae where all the common variables have been switched out with different letters and symbols.. and see if they still get it right. You’d be surprised how long it takes to get some of these right.
    Anyway, that was only semi-related, but I thought it was interesting.

  13. Topher says:

    Why do I have to type more code to get the same thing accomplished.

    If I type myobject.setProperties( 100,100,10,1 );
    First I am not a moron, I wrote the function so I know what the parameters are, or
    second, if I did not write the function most modern C++ IDE’s will pop up a box that shows you the function declaration and the names of the parameters it expects as you are entering the parameter values.

    So, [myObject setPropertyX:100 y:100 width:100 height:100]
    is completely extraneous and does not solve the problem of knowing what parameters the function requires because it explicitly requires you to both know AND type in the names of the parameters redundantly.

    Second, and it surprises me how much this is ignored by people writing articles about how great Objective C is compared to . notation, I can’t stand having to go back over a line of code I written to make sure my brackets are inserted appropriately.

    When typing something like

    MyObjectA.MyPropertyObjectB.PropertyValue = 4;

    I can write from left to right, end the line with a ; and go on to the next line of code, with Objective C it is NOT intutive to know you have to start the line with three [[[ to nest accessing the properties of the objects until you finish the line of code. It seems like every line of Objective C you write has to be reviewed for bracket completeness and is just not efficient. Perhaps XCode these days will auto complete brackets for you, but this was the most major pain in the *ss with objective C programming is that it just seemed unintuitive for writing code.

    The retardedness of Objective C is exemplified in this statement as mentioned:
    [myObject setX:[myObject x] + 15];
    where myObject.X += 15; is succinct. There are a lot more instances where the weakness of Objective C and bracket notation was resolved with dot notation.

    Why do I have to write more code to achieve the same result? Objective C is just Apple’s attempt to hold on of the few “innovations” Apple developed that hasn’t been replaced by something standardized by other companies and organizations. Objective C is the only reason why I don’t run out and buy a Mac and start developing Mac apps because when using languages like C++ and C#, Objective C is grounded in the stoneage of software development.

    • Preston says:

      Topher:

      “Why do I have to write more code to achieve the same result? Objective C is just Appleโ€™s attempt to hold on of the few ‘innovations’ Apple developed that hasnโ€™t been replaced by something standardized by other companies and organizations. Objective C is the only reason why I donโ€™t run out and buy a Mac and start developing Mac apps because when using languages like C++ and C#, Objective C is grounded in the stoneage of software development.”

      Apple didn’t develop Objective-C. Your assumptions about why it’s still used are silly, and calling it the “stoneage of software development” is ridiculous, especially compared to C++ which garners feverish levels of criticism these days. I think you’re just used to C++ and C# and don’t like learning the language differences. If a superficial syntax issue like brackets prevents you from using the entire platform, you’re letting bias get in the way of knowledge. You get used to the brackets after like half an hour. New C programmers think braces and semicolons are weird and cumbersome too.

      When you go back to C++ or C# with its unlabeled method parameters, you realize just how much you prefer Objective-C’s syntax.

  14. Paolo says:

    I feel Objective-C cluttered by its syntax. Compare it ruby, which currently looks like

    myObject.properties ๐Ÿ˜ก => 100, :y => 100, :width => 100, :height => 100

    and it’s about to become

    myObject.properties x:100, y:100, width:100, height: 100

    No square brakets, no semicolons, no redundancies. Just the code that does the job.

  15. Anon says:

    @Paulo

    myObject.properties ๐Ÿ˜ก => 100, :y => 100, :width => 100, :height => 100
    or
    myObject.properties x:100, y:100, width:100, height: 100
    vs
    [myObject setx:100 y:100 width:100 height:100];

    Sorry, but I don’t see how the Ruby example is better at all. The extra commas are “redundant” for a start. And the older Ruby example is absolutely hideous and cluttered. For a supposedly modern language like Ruby, it says a lot that it was heavily bested by 24 year old Obj-C, a supposedly ugly language according to Ruby fans like yourself.

    Also, your last sentence would be more accurate as:
    “Just the code that does the job, slowly”

    @Topher
    Why do you bring up IDEs as a way to solve the lack of parameter identifiers for functions in C++, but then ignore them completely when you complain about typing in Obj-C methods? One hardly ever has to type a full method name in Xcode. Again, Xcode does a reasonable job of filling in the square brackets these days. I could bring up historical problems with C++, like compiler support, but it’s silly in a discussion about the state of languages today.

    You complain about
    [myObject setX:[myObject x] + 15];

    but I would call that code smell. What you are dong is ugly, so it should look ugly. You should implement an incrementX: method. This kind of concept is probably unfamiliar to you as you appear to be more experienced with languages like C++ that are, shall we say, not quite an ideal realisation of OOP. See: http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

  16. Nick says:

    Thanks for putting your thoughts down. The dot notation seems easier to identify simple coding errors.

Leave a Reply