Aug 6 2009

Dot-notation Syntax

When I teach, I always make sure to mention the dot-notation addition to Objective-C 2.0. Then, I make sure to tell the students never to use it ever, ever, ever again. But why? Why this seemingly irrational hatred of dot-notation? Is this a style choice and us “bracketeers” are being hard-headed? The answer is no, we are not being hard-headed, we are keeping our code consistent and maintaining readability.

The Intent of Code

The naming conventions used in Cocoa and Cocoa Touch are clear and straightforward. When we look at well written Mac or iPhone code, we can tell exactly what is going on by glancing at it. That’s the power that Objective-C gives us. If I want an object to take a drink of water while doing a cartwheel, I send it the message:

    [obj takeDrinkOfLiquid:water whileDoingCartwheel:YES];

We know exactly what that means. There is no room for interpretation. Likewise, we know exactly what this line of code does:

    a = b + 5;


This adds b and the value 5 together and assigns the result to the variable a. We get these operators, = and +, from the C programming language. We have a lot more operators in C, like *, /, -, % and &. And we know what all of those operators mean. When we see them, we say stuff like, “That’s a division!” or “That’s a subtraction!” Except we don’t say that. We don’t even think about that. We instantly know.

Another operator that is commonly used in C is the . operator. The dot operator accesses a member of a structure. It goes to an address in memory (the address of the structure object) plus an offset. That’s all it does. We instantly know what it means.

Sometimes, an operator may have another meaning depending on the context. For example, the * operator could be dereferencing a pointer or it could be doing a multiplication. However, the context this operator is being used in allows us to easily discern which operation is occuring. The dereferencing * is a unary operator and the multiplication * is binary operator. When we look at code, we know which one is being used.

    int a = *ptr; // Definitely a dereference!
    int c = a * b; // Definitely a multiplication!
    int c = a * (*b); // Definitely both!

In Objective-C, the square brackets ([]) were added for message sending. While the square brackets had previously only been used for indexing an array, the intent of the brackets can be easily determined by the context.

    [object message]; // Definitely a message send!
    int a = variable[index]; // Definitely indexing!

With that, we can say that we definitely know what the operators in Objective-C do with a quick look.

Then comes Objective-C 2.0…

With Objective-C 2.0, we get dot-notation. Many programmers new to Objective-C like dot-notation, it reminds them of other languages that they are more proficient in. Except for dot notation doesn’t do the same thing in Objective-C as it does in other languages.

Dot-notation in Objective-C invokes an instance method. Code in a method definition is executed when this dot is used. This code could be simple and it could just return a value. That doesn’t cause much of a problem. However, what if that method is a lot beefier:

- (int)value
{
    NSData *valueWrapper = [NSURLConnection sendSynchronousRequest:...];
    if(valueWrapper)
    {
        const int *v = [valueWrapper bytes];
        return *v;
    }
    return -1;
}


That method could go wrong in a number of ways. When we see the invocation of that method with dot-notation, all we see is:

    int x = foo.value;


What does that mean? Are we getting the value field out of the structure object foo? Are we executing a simple method that returns a value? Or, in this case, are we creating a network connection, pulling a value from a web server, turning that data in to an integer and then returning it?

It is ambiguous. With dot-notation, we don’t know exactly what this code means at first glance. When we see this code:

    int x = [foo value];


Our first glance tells us we are definitely sending a message. That clues us in that more work is being done, not just a simple memory offset and an assignment.

What is more confusing, especially to Objective-C newcomers, is invoking a setter method with dot-notation.

    foo.object = otherObject;

In C or C++, this is a simple assignment. In Objective-C, this could easily be creating a copy of otherObject or retaining otherObject. It is not immediately apparent from that line of code. The difficulty of understanding reference counting as a beginner gets amplified by code like this. Our code takes longer to read. We have to dig around to determine what is actually happening in this line of code.

Same context, same operator, different operation. We don’t know what this operator does anymore.

Return Values

Here is another example:

    someView.frame.size.width = 30;

Very straightforward, we’re setting the width of a view’s frame to 30 pixels.

Actually, no. We are not. We’re generating a compiler error. The value returned by a dot-notation invocation is not an lvalue. We can’t assign it anything. However, if someView is a structure, that line of code will work as intended.

    someView.frame.size.width = 30; // This is valid code!

We lose consistency in our code using the dot operator. An operator in the same context, one is valid code, one is not. (It’s also a good thing that first line generates a compiler error, otherwise, we’d only be changing the copy of someView‘s frame, not the instance variable of someView.)

Now, that is confusing.

But I’m used to C#, C++, Java. Dot-notation looks like I’m at home!

You aren’t at home. You’re working with another language.

If one language solved all problems, everyone would use that language. Each language and API is a tool and it has an intended use. Using dot-notation in Objective-C would be akin to pounding nails in with a screwdriver. Sure, it works most of the time, but it isn’t the best use of a screwdriver or the best way to hammer nails. Eventually, you might smash your own hand.

Users of dot-notation are typically new to Objective-C. This is most likely the intention of dot-notation; a more familiar syntax for programmers coming from other languages. However, you would be better off familiarizing yourself with Objective-C then pretending it is another language. You will spend less time confused and more time solving a bigger problem.

Apple uses it in their sample code, though!

That’s right, they do. Now, despite what the kool-aid is making you think, Apple does occasionally get something wrong. Their sample code has always been hastily crafted to get developers to use their platform. It is not always the best example of how to use a language.

It is my belief, after teaching roughly 300 students Objective-C, that dot-notation is confusing. It hinders the main goal of software development: writing maintainable, effective, efficient, easy to read and bug-free code.

In the end, there is wrong way and a right way to write Objective-C code. I will not say that using dot-notation is the wrong way. It is an acceptable way to write Objective-C code. I will, however, say there is a better way to write your code. The better way does not include dot-notation.

69 Comments

  1. Gubatron

    I’ve tried hard to like those brackets, but this language is so weird, specially when it comes to declare a method and it’s parameters

    - (retval_t) forward: (SEL) sel : (arglist_t) args

    wtf?? it’s just crazy, I’m sorry. Nothing like straight forward declarations, like in Python, or Java

    def method(param1, param2):

    or

    public String getContent(int param1, Object param2);

    Anyone can read that without a manual

  2. Daniel Jalkut

    Thanks for writing about this. I agree with you, and it’s the ambiguity and inherent lack of readability that keeps me allegiant to brackets.

    I find documentation and sample code especially annoying since Apple adopted dot notation as their standard. I always switch their dot notation back to brackets when I am borrowing code.

    Daniel

  3. Mark Miller

    this was a good post, joe.

    in EACH example above, i wish you would have compared the wrong way to write code using dot notation with the right way of writing code by NOT using dot notation.

    please consider updating your post to ensure that new programmers can see the differences.

  4. Chris Hanson

    I disagree most emphatically. The whole point of dot notation is that, when combined with properties, it’s not *just* an alternative syntax for invoking methods. In fact, if that’s how you think about dot syntax, STOP. That’s not what it’s for at all.

    What dot syntax and property declarations are for is separating object *state* from object *behavior*. Classical OOP only really defines objects as only exposing behavior but the past 30+ years have demonstrated rather aptly that objects consist of both. C# was actually pioneering in this; its concept of properties is rather similar to what the combination of property declarations and dot syntax enable in Objective-C.

    To write idiomatic Objective-C 2.0 you should use @property to declare properties, and use dot syntax to access them. Period. Doing otherwise is a bad idea because it will create code that isn’t intention-revealing to other experienced Objective-C 2.0 developers. Teaching students to do otherwise is doing them a disservice, because you’re directly contradicting those responsible for the language and its evolution.

  5. Aurélien Hugelé

    Good summary. ObjC 2.0 worst “enhancement” is the dot notation syntax.
    Mixing C code and ObjC was really natural, now it is not due to those nasty “.” which are really confusing.

    I’m not even talking about things like :
    NSEnumerator *anEnum = myArray.objectEnumerator;
    which is simply confusing. Is it an accessor? so where is the property? can I use setObjectEnumerator: ? oh no sorry, it is just a method… or maybe a stuct field…. or whatever I don’t know…
    I think Apple wanted to please people who found the [] notation tedious.

  6. Kevin Ballard

    Dot notation is only confusing if you don’t know what object you’re talking to. If you don’t know whether you’re using the dot operator on a struct or an object, you have bigger issues than the confusion over what operation you’re performing.

  7. isaiah

    so, forgive me for oversimplifying, but it seems to me that the argument that you’re making is that dot notation *can* be used to produce very confusing code.

    i don’t disagree, but i can say the same about so many different syntaxes, patterns, and idioms.

    a good example is #define. with the preprocessor you can do all sorts of nutty crazy things that will make your code completely illegible and inconsistent. not only *can* you do crazy things with the preprocessor, but it makes it easy. in fact, the number of good things that you can do with it is limited to the very simple and the very elaborate.

    but that doesn’t mean that #define is useless. far from it, in fact. it just limits its utility. never using #define because it *can* produce bad code would be silly.

    i don’t think it’s difficult to come up with a few examples where dot notation might improve your code in some way. there must be at least one or two, right?

    so, maybe, “never to use it ever, ever, ever” is a bit overzealous, no? perhaps, a more measured conclusion would be to limit its use to areas where you understand it and it will be both useful and unambiguous.

    isaiah

  8. Chris H

    Joe, thank you for blogging/speaking up.

    My experience of introducing/teaching Objective-C to experienced programmers from other languages validate one of your main tenets — it’s an unnecessary potential confusion for new-to-ObjC learners.

    Mark Miller’s comment (on more illustrative example codes) is worth taking note, as I’m confident that this post will be visited many times over.

    From halfway around the world,
    Chris

  9. Piet

    I can see your point, even though I don’t completly agree with you. What bothers me is this sentense:

    “It hinders the main goal of software development: writing maintainable, effective, efficient, easy to read and bug-free code.”

    Well, no, I don’t think so. The main goal of software development is solving someones requirement. If you code looks dirty or you use the dot syntax is not *that* important, as long as it the software helps the people who will be using it.

  10. Miles Tinsley

    As a relatively new Objective-C/Cocoa developer, this has helped focus my understanding of the language and maintain consistency and elegance in my code. Thanks!

  11. Trevor Squires

    I’m certainly not expert enough to be an instructor in obj-c or cocoa so it’s with a lot of deference (but not much flowery/gentle wording) that I have to say: I really can’t get behind your examples given your stance of “never ever” use it.

    Saying [foo value] clues you in that more work is being done is imho completely false for 2 reasons.

    1 – The name you’ve chosen conveys nothing beyond a simple getter (pre dot-notation style) so there’s really no cue that anything special is going on.

    2 – In fact, it’s only if you typically *use* dot notation might you be alerted that this poorly-named method (not a @property) is doing something unusual. There must be a reason the guy who wrote ‘value’ didn’t declare it as a property… I wonder what that is?

    As for assignment, how does [foo setObject:anotherObject] convey anything more about copying vs retention or simple assignment than foo.object = anotherObject?

    If anything, the dot notation tells me that if I want to know whether anotherObject will be copied/retained/assigned, I need only to look at the contract specified by the @property.

    As for someView.frame.size.width = 30 … it’s the same compiler error you get from [someView frame].size.width = 30 (right?).

    So really, the problem is that self.violating.demeter.evil = YES (assuming violating and demeter both return objects).

    I’ll certainly concede that. It does look too similar to poking into structs but the fact is, bracket notation doesn’t save you from this type of LoD violation – [[[self violating] demeter] setEvil:YES] is just as bad and just as potentially broken.

    I do appreciate the article – it’s certainly good to think about these things :-)

    Regards, Trev

  12. Amos Wenger

    Although I like the post, and the point made, I think these concerns are irrelevant in a high-level programming language, and here’s why: http://amoswenger.tumblr.com/post/157845512/dot-syntax

    In a nutshell: calling a setter or assigning a field is expressing the same intent, ie. “adjust a value”, and that’s a lack of abstraction, ie. it doesn’t hide implementation details enough. Performance concerns (e.g. how much work is done in the setter) is useful in low-level languages only, imho.

  13. tmk

    First thanks Joe for the article, it made for a really interesting reading it’s great indeed to reflect on this subject.

    But FWIW, I’m with Chris Hanson and Trevor Squires on this matter.

    IMHO, dot notation works better to convey the intent of the code (and in that context it makes for a quite natural extension to the dot used in structure members).

    I heartily recommend the following blog by Chris Hanson (and this comment thread) on the same subject http://eschatologist.net/blog/?p=160

    = tmk =

  14. Benjamin Ragheb

    You are basically saying you don’t use dot-notation syntax because it makes YOUR job easier as a teacher, especially to students who have a weak grasp of the language to begin with. You are not thinking of working programmers.

    Making a synchronous network call in a property accessor method is ATROCIOUS style, you should teach never to do it. But if your philosophy is to avoid every language feature that can be abused, you might as well avoid method calls altogether (you don’t know WHAT they’ll do!).

    Yes, knowing how to interpret someView.frame.size.width depends on knowing someView’s type. Knowing how to interpret a line of code without context is NOT a valuable feature of a language. Besides, only in pathological example code would a struct be named “someView” and have a “frame” field.

    Dot-notation syntax is not there to make things easier for people new to Objective-C, you have clearly demonstrated that. In fact, it’s an additional thing to learn if you are new to Objective-C; it’s one more thing to teach if you are teaching Cocoa programming. So STOP BEING LAZY and TEACH IT, you are doing your students a disservice.

    You are basically saying to your students, “don’t use dot-notation syntax, you’re too dumb to figure it out.” I hope that’s not the case. I hope I never have to work with somebody who rewrites my dot-syntax code, because somebody at the Big Nerd Ranch “told him so.”

  15. Christopher Lloyd

    Chris Hanson, where is the line between state and behavior. e.g. UIViewController.view’s side effect of loading nibs as a getter. Obviously the rest of Apple didn’t get your memo.

  16. Joe Conway

    I’m glad we can have a discussion about the dot syntax. We can freely state our opinions so that each developer can make their own choice. As with anything in life, if there are multiple choices to get the same result, everyone will filter in to one of the camps. (Although, it is disheartening to see the angry rhetoric used by some in discussing something so trivial. Perhaps the solutions to some of our problems could be reached by going outside and taking a deep breath before we hit send.)

    If I were to continue arguing this point objectively, I could start by saying that the naming conventions of accessors tell us whether or not we are accessing an object’s state versus performing some action. We were fine before the dots came marching in and I’m definitely in the “If-it-ain’t-broke-don’t-fix-it” camp for many of my life’s pursuits. I could also say that when you have an application where you are using structures as much as you are using objects, dot notation becomes a huge burden. (In games, where we must drop down to C for vectors, matrices and quaternions, etc., dot notation presents a serious clarity problem.) I might also mention that in Apple’s documentation, dot notation is defined as “purely syntactic sugar” (or “a compact and convenient syntax you can use as an alternative to square bracket notation”) and any attempt to say it actually means something is not documented. I would also argue that dot notation is very confusing for newbie Objective-C programmers, because I have seen it confuse them time and time again. Even though the points that Chris Hanson makes are good, I don’t think the tradeoff is worth it.

    This is my opinion, backed up by my experiences. There are merits for both sides of the argument. At the end of the day, people need to make choices for themselves. This post is more information for those that are trying to make that choice, not for those who have already made it. It is intended to persuade because I’d like for everyone to be in my camp. I like my camp. I think the reasons for being in my camp are valid and important. I promise we will roast marshmallows in my camp, too. But, I understand if you want to be in the other camp. That’s okay, we can still be friends. Maybe some light-hearted teasing every now and then. Also, I reserve the right to call you “Dottie” for fun. But you should be in my camp. If not for any of the reasons above, but because in my camp, you get a free t-shirt and the aforementioned marshmallows.

  17. Ed Voas

    The comment about UIViewController.view doesn’t hold water with me. The intention is that when that returns, you have the view. If it loads it lazily, what do I, as the caller, really care.

    The fact that it loaded something from a nib to provide a lazy-inited state does not make it behavior (to me, at least).

  18. Duncan Wilcox

    Syntax sugar is a slippery slope. After years of C++, ObjC1 was a shock, but it was refreshing to visualize the cost of code in the form of more screen real estate.

    Dots aren’t quite C++ operator overloading, but cost and side effects of method invocations are definitely less visible, newcomer or not.

  19. Edward

    I think it’s a problem if one see it as a problem, ie it’s all in the eye of the observer. Would it have been a problem if the dot syntax had been in Objective-C from the beginning? As for myself I think the glass is half full and as an “old” programmer I have to actively embrace and learn new things and I don’t see the dot syntax to be such a huge watershed. I think it sounds more like Joe might have been staking for Objective-C being “perfect” too long and can’t accept it being changed (ie was not really “perfect” before). Ask yourself what who is more professional? Someone that has learnt the dot syntax and how it should be used or someone from a BNR course that won’t use it because “Joe said so”. I have attended a couple of BNR courses and I reading this kind if attitude makes me sad.

  20. Jason

    As mentioned, perhaps banning the dot-syntax is a bit harsh. It is something that developers will see in the wild. I agree with the author’s premise – it is confusing – and if you don’t know how it differs from other languages – you should avoid using it.

    (The same could be said of the synthesize getter/setter shortcuts: Do it the long/hard way first, until you can appreciate what synthesize and properties gives you.)

  21. Georg Tuparev

    I write Objective-C since 1991. I was teaching too (and still do it with new colleagues). When I first read about the new dot syntax my reaction was very negative. I was expecting the same mess as Joe describes. But slowly I understood that the new syntax makes my code not less but more readable. It shows the intend. It tells me if I am accessing a property or a non-accessor method. And yes, this IS important distinction. I am 100% with Chris Hanson on this.

  22. Döme

    Dot-notation in ObjC would not be as bad, if it was used consistently and carefully. But, even in Apple’s own frameworks, that isn’t the case, as the UIViewController.view example illustrates. How do you expect other, less experienced programmers to use it?

    The bigger problem is clarity, though. You might not always have the context on-screen that helps you determine what exactly a given dot does, and having to look up the variable or class definition just to figure out if it’s a struct or ObjC object takes time, and when you have to read, or worse, debug, other people’s code, not having this bit of information right there costs time.

    Dot-notation makes sense in languages where it is really idiomatic, but in ObjC, that is just not the case.

  23. Keith Bauer

    @Chris Hanson: I wouldn’t mind following the evolution of the language, but sometimes (Java 5 Generics, ObjC 2.0 dot notation) the language designers get something so badly wrong that it is worth “rebelling”.

    For me, there are three killers about dot notation:

    1) The LHS must be statically typed. My ObjC code is full of “id”; it avoids a lot of typing without giving up a lot of safety, and it makes code significantly easier to refactor. With dot notation, the LHS of every dot must have a static type, so all the benefits of being able to use “id” in other contexts quickly vanish.

    [Together with the newfound insistence on protocols being formally declared, this makes me feel that the designers of ObjC wish that ObjC were Java. What's next, generics? ObjC isn't supposed to be Java, it's supposed to be SmallTalk]

    2) As Joe says, “something.bounds.origin.x = 3.0f” may or may not be valid code; it’s impossible to tell at a glance; you must know whether “something” is an object or a struct. I rather like knowing what my code is doing; it’s one reason I dislike C++ that there are innumerable hidden things happening behind my back.

    3) Even if a class declares -p and -setP: methods, you can’t use the dot notation unless it declared an @property p. That means that in the presence of “legacy” classes, as in Mac OS X programming, the dot notation cannot be used consistently. If your code’s full of [o p] and [o setP:x] then having some o.p and o.p=x is just extra-confusing.

    I don’t see why 1) is necessary at all (if o.p is equivalent to [o p] and o.p = x is equivalent to [o setP:x] why does o need a static type, when it doesn’t for those message sends?) so perhaps that could be fixed.

    2) could only be fixed by having chosen a different piece of punctuation than the dot. @, #, `, .., there were plenty of possibilities. Why use the one that results in ambiguities?

    I don’t see why 3) is necessary. If the object doesn’t have an @property corresponding to use of dot notation, why not look for equivalent methods?

    There is one situation where I don’t mind dot notation, and that’s as private helpers for managing the retain count of ivars. “self.” doesn’t carry the same ambiguity that “something.” does, and self.name = aString; in a few places in a class is a bit nicer than a bunch of [self setName:] calls.

  24. Niklas Alvaeus

    This is silly. Apple use the dot notation extensively, so how can you run a course and recommend students not to. Will just confuse even more instead of just teaching it. Get with the program.

  25. Chris Hanson

    @Keith Bauer:

    Your point 3 is incorrect. You don’t need to use @property to be able to use dot notation with it – specifically to support using dot notation with older code that hasn’t been adapted to use @property yet.

  26. Keith Bauer

    Whoops, so I don’t. I wonder why I thought that. Thanks for the correction, and sorry for the misinformation.

  27. tmk

    With all due respect and speaking as someone who has attended 4 BNR Bootcamps so far starting with Cocoa Bootcamp with one of the classes of

    As I already mentioned discussing the merits and caveats of the dot notation is instructive as is demonstrated by this thread.

    But as their instructor, telling students “never to use it ever, ever, ever again” does seem misguided.

    Seems too extreme and does not leave room for the students to make their own informed decision.

    That said, the marshmallow are tempting ;-)

    = tmk =

  28. tmk

    … classes of 2004.

    = tmk =

  29. Steven Vandeweghe

    When I’m debugging code and I notice that a variable has an unexpected value, I often search my project to find out where the value was set. If the variable is named foo, I can simply search for setFoo. Using dot-notation would make that more difficult I think.

  30. John C. Randolph

    ” If the variable is named foo, I can simply search for setFoo.”

    You can also search for “.foo =” just as easily.

    I’m going to weigh in with Chris and Georg on this. Dot notation is a handy thing, you just need to be careful not to abuse it.

    -jcr

  31. Scott Lewis

    Well, I’m a month late coming upon this posting, but I found it with such relief that I thought I would comment anyway. I have found dot notation to be such an abomination that I routinely translate Apple examples out of dots and into brackets.

    I wonder if what is really at the root of this (quite civil) debate is the “dual-soul” that Objective-C has, as it is both a C-language, and an attempt to emulate Smalltalk. I’m primarily a Smalltalk programmer, so for me the awkwardness in the language comes from it not being Smalltalk enough, while I see others are a little distressed by its actual Smalltalk elements.

    Personally I find that conditionals expressed in Obj-C are quite awkward, and really interrupt the object-message format. In Smalltalk instead of using if(condition) { statement; statement;} you use a structure like this:

    (condition) ifTrue:[statement. statement] ifFalse: [statement. statement].

    This preserves Object-message, as condition returns a Boolean object (well, usually Boolean is the abstract super class, and False and True are the concrete subclasses), which is then sent ifTrue: ifFalse (and you can use one or both, depending on your needs, though usually if you use both this indicates your code is not properly optimised.) You can also (in most Smalltalks) send condition ifNil: and ifNotNil:.

    Of course, it would take a special millenial alignment of planets probably for Obj-C to add this even as an option, as its current conditionals are one thing “real C programmers” are most welded to.

    What really puzzles me is why Apple chose to implement fast enumeration in the manner it did, using what seems most like Python syntax. The Smalltalk syntax, in the context of Obj-C, would have made more sense (particularly as it is also “borrowed” by the increasingly popular Ruby, though in what seems to me a syntactically awkward form). This looks like:

    collection do: [ :each | each message ]

    But (just to really outrage diehard C programmers) what I really, really want is something like a vastly improved XCode that offers (at least as an option) something like the CHB (Class Hierarchy Browser) that is common to most Smalltalks. Every time I open XCode after working in Smalltalk, I feel as though I’ve had to go back in time about 20 years or so. Instead of presenting code for each object in a single vast file (I mean, come on, how inefficient is that?) the CHB presents a list of all the Classes that are in scope. You select a class, and it brings up a list of the methods for that class (you can choose Class or Instance methods). If you want you can also choose to display the inherited methods as well. Select a method, and the code for the method comes up in the editor. Really efficient, and easy to navigate.

  32. Andre

    On Xcode enhancements:

    I have noticed that in Xcode 3.2 properties now show up in the ctrl+2 drop down so it is now even faster to check if something using the dot notation is actually a worker method or a setter/getter.

    “You select a class, and it brings up a list of the methods for that class (you can choose Class or Instance methods). If you want you can also choose to display the inherited methods as well. Select a method, and the code for the method comes up in the editor. Really efficient, and easy to navigate.”

    Don’t we have the ctrl+2 (method/ivar navigation), ctrl+6 (class navigation) popups for this when the insertion point is in a code editor window? Also there is a class browser that is really fast. And it updates on scope changes IIRC.

  33. Steven Degutis

    Joe,

    Your post does not state an opinion, it’s simply giving bad advice. To sum up: you’re telling people “don’t use the tool because you might not know how to use it” when your real message should be “learn how your tool works and whether it’s right for you before using it”.

    A more in-depth response to your blog post is at the following link:
    http://www.degutis.org/dev/2009/10/17/dot-syntax-wars-the-definitive-answer/

    Now, a few comments on your comment…

    “If I were to continue arguing this point objectively…”

    Heh! Nothing in your blog post was “objective”, in fact it’s very clearly stated in there that it’s “better” to not use dot syntax.

    “We were fine before the dots came marching in and I’m definitely in the “If-it-ain’t-broke-don’t-fix-it” camp for many of my life’s pursuits.”

    If Apple had this same philosophy, wouldn’t we still be manually updating our view and model classes without any help from KVO or bindings, or Core Data, or any of the technologies that your career depend on?

    “It is my belief, after teaching roughly 300 students Objective-C, that dot-notation is confusing. It hinders the main goal of software development: writing maintainable, effective, efficient, easy to read and bug-free code.”

    So, Joe, let me see if I understand your *real* point here… basically, *new* developers should not learn the dot syntax right off the bat, but should get a deeper understanding of KVC/KVO first? Because that seems very inline with *the entire rest of your blog post*, but also *contradicts your main point*.

    “This post is more information for those that are trying to make that choice, not for those who have already made it.”

    All the more reason for you to be responsible about what message you send! Don’t tell people “this API is bad, stay away!” when it’s really just the beginners who are having trouble understanding it.

  34. Mike

    I really don’t have a dog in this fight. I’m a VB.NET programmer who is learning Obj-C specifically to port/create some software for the iPhone. I’ve been doing this for less than a month.

    As I’m reading through HeadFirst iPhone development (GREAT! book, BTW), I come to page 110.

    The topic at hand is memory management, which is still a little fuzzy for me on this platform. .NET has garbage collection and what I consider to be fairly straightforward memory management techniques.

    Anyway, page 110 is a Q&A page, and one of the questions is:

    “Do I have to retain things I want to set on my properties?”

    The answer in the first paragraph is basically “no.” Then, they add this paragraph:

    “One more quick note: the automatic retain/release ability of properties only works if you use the “.” notation. If you explicitly modify the field that backs the property, there’s nothing the property can do about it and can’t retain/release properly.”

    Again, this is a bit of a fuzzy area for me, but let me see if I could break this:

    (in @interface section of .h file):

    IBOutlet UITextField *notesField;

    (after @interface section of .h file):

    @property (nonatomic, retain) UITextField* notesField;

    (in .m file):

    @synthesize notesField;

    Now, what happens here:

    [notesField setText:@"This is my new text."];
    notesField.text = nil;

    Am I missing their point, or does the first line above not increment the retain count and the second line decrements it (so retain count would == 0), so my object could be cleaned up at any time?

    Is this a valid reason to use dot-notation in code?

    Thanks for helping me!

  35. Joe Conway

    @Mike: Unfortunately, the book you are reading is incorrect.

    The dot operator is just shorthand for invoking an accessor method.

    foo.x = newObject;

    is equivalent to

    [foo setX:newObject];

    Both of these lines of code will do the exact same thing. Let’s say the property X is flagged as retain, both of these lines will: retain newObject, release the old value X currently points to, and set X to point to newObject.

    The book you are reading is attempting to say that using the -> operator to access an ivar will not perform the memory management. That is correct, but it is useless information. It is rare that you will see public ivars in Objective-C classes that are referenced by the -> operator. If you ever find yourself trying to do that, you should be creating a structure instead.

  36. Terry Grossman

    My only comment is that your statement “never to use it ever, ever, ever” is so arrogant that I would not want to be one of your students. Other than that, I agree with many of your points.

    Cheers

  37. DT

    “It is my belief, after teaching roughly 300 students Objective-C, that dot-notation is confusing. It hinders the main goal of software development: writing maintainable, effective, efficient, easy to read and bug-free code.”

    I could list a few dozen things about Objective-C, Cocoa, and Xcode which “hinder the main goal of software development: writing maintainable, effective, efficient, easy to read and bug-free code.”

    Which is why I tell clients that that they can have their Mac apps developed in REAL Studio or Xcode, but the estimate for Xcode is 3-4x.

    Of course Cocoa Touch is the only game in town for iPhone.

    Having gotten that off my chest, I agree that dot notation in ObjC can be confusing, and limit its use to properties only. (That is, when I’m developing an iPhone app, or on the rare occasion a client demands an Xcode project.)

  38. Preston

    As long as someone is able to do:

    anObject.retain;

    Or:

    NSString *uppercaseString = aString.uppercaseString;

    …without compiler error, dot-notation will be something I avoid, because for all the talk about how it separates state from behavior, the compiler doesn’t care either way. You’re free to call any parameter-less behavior methods using dot notation. I don’t want people misusing my methods as getters when they’re not getters, and unfortunately, the @property declaration isn’t used by the compiler to enforce my intent.

  39. Jack Zahran

    @DT “I agree that dot notation in ObjC can be confusing, and limit its use to properties only. ”

    Yes, that is dot notations intended use in ObjC, with Properties only. In Xcode, you’ll notice auto property completion for dot notation works very well. And, it gets better with Apple’s frameworks as they update them. UIKit fully supports this now.

  40. Diogo

    I’d like some sample alternative code, too. Though I’m convinced not to use dot-notation in ObjC, I still can’t translate the following code to message notation:

    frame.size.width

    If I change it to:

    [[frame size] width]

    I get a myriad of compiler errors, depending on the situation.

  41. John

    I wonder if Apple gave the option to program objective c OR java OR c#, what programmer’s would choose? If they all compiled to a clr like .net, I’m positive objective c would be used in about 2% off apps out there and dot notation languages would be primary.

  42. hcm

    I didn’t realize anyone would mind whether it was written one way or the other. I’ll be more coding conscious from now on.

  43. BytesLand

    I like dot notation to distinguish between real “operational” methods from simply accessors… You just type a dot and voilá, every available property shows up.
    In fact I don’t like gratuitous accessors at all, but using properties for the few things that really belong to the class interface rather then the impl. details looks very clear and allows for the customization needed once in a while writing the methods yourself.
    It really makes much more clear wether something is retained, copied or thread safe just by looking at the class header.

  44. Mike

    I’m the same Mike from 12/14/2009.

    Since that time, I’ve learned a lot about iOS programming, and I actually took Joe’s iPhone OS course in February 2010!

    I still program in .NET for a living, and almost a year and a half later, I’m about to start (hopefully) helping some IT professionals here at my new job learn about programming for iOS.

    I plan to give them this article and hopefully get them to at least learn enough to decide for themselves whether dot notation is useful.

    For me, coming from a Visual Basic perspective, dot notation adds nothing I can’t accomplish with (IMHO) more readable messages, and it doesn’t do nearly the same thing that dots do in .NET. Maybe if you have a different background the dots can be very useful, but I also find myself “fixing” Apple’s boilerplate code to remove the dot-syntax.

    When I was taking the class from Joe, I brought up this article and asked him why he was so adamant. If I remember correctly, his argument boils down to the fact that Obj-C dots “do something”, whereas C dots just read or assign values. Sure, Obj-C dots fill a similar purpose most of the time, but the Obj-C dots tend to hide the fact that there is at least the POTENTIAL for a lot of processing to be occurring in the background. When you use the bracket syntax, it’s much more obvious that you have to consider what might be going on behind the scenes during that line of code.

    Joe, I’m with you. Plus, your marshmallows are tasty!!!

  45. Sarah

    The whole notation thing makes life a lot easier in .NET and this is what the older programming languages lack.

  46. jbm

    I’ve only started using dots lately, but I kind of like them, to be honest. I only use them for accessing @properties (obviously), and personally I like the look of the code, since it’s now really obvious what’s a property and what’s a method.

  47. Don

    I have to 100% disagree with Chris Hanson on this one. I don’t mean to sound condescending but how can someone with your level of experience not realize the value of encapsulation? Using message passing syntax consistently for uniformly accessing state and behavior successfully hides the implementation details of the object. Using dot notation to differentiate ‘state’ access vs ‘method’ access completely defeats the purpose of objects as black boxes. Once correctly written they are only responsible for answering questions sent to them, and successfully hide their own implementation enough so that whoever is asking the question NEVER has to care about ANY of the details in how the answer was computed.

  48. Donald

    I have to 100% disagree with Chris Hanson on this one. I don’t mean to sound condescending but how can someone with your level of experience not realize the value of encapsulation? Using message passing syntax consistently for uniformly accessing state and behavior successfully hides the implementation details of the object.

    Using dot notation to differentiate ‘state’ access vs ‘method’ access completely defeats the purpose of objects as black boxes. Once correctly written they are only responsible for answering questions sent to them, and successfully hide their own implementation enough so that whoever is asking the question NEVER has to care about ANY of the details in how the answer was computed.

  49. Donald

    On another note, I am so sick of the mindless misuse of the ‘right tool for the right job’ argument. There are some things that are just plain wrong in the design of the language which violate proven principles. These quirks should never be used…for any job. Everything feature should be evaluated pragmatically for its strengths and weaknesses, and believe it or not there are things out there whose ONLY ‘strength’ is “well people are used to things that look like that so why not?”.

  50. Donald

    @Scott Lewis. I also totally agree that the procedural control flow in objective-c really breaks with object orientation. There are some ways around this, however, though we can only go so far as in the end C is still there, as much as we’d like to avoid it most of the time.

    With the introduction of blocks in IOS4 it is now possible to write abstractions around procedural control flow. For example, by (somewhat hackily) adding methods to NSObject (and therefore NSBlock, which is private) we can achieve something like this:

    int count = 1;
    [^(){ return count <= 10; } whileTrueDo: ^(){ NSLog(@"%d", count); count += 1; }];

    Adding methods to collections (or just using the rather poorly named enumerateObjectsUsingBlock: method of NSArray) we can do something like this:

    id collection = [NSArray arrayWithObjects: @"1", @"2", @"3", nil];

    [collection forEachDo: ^(id element){ NSLog(@"%@", element); }];

    Booleans are a problem since they are implemented as primitives. We can write a wrapper and add methods to it, but this is pretty cumbersome. This is the price you pay for not being object oriented all the way through though..

    [[OOBoolean booleanWithBOOL: ( 1 == 1)] ifTrueDo: ^(){ NSLog(@"All good"); } ifFalse: ^() { NSLog(@"Bad times."); }];

    Same issue with integers, though there we at least have existing wrappers we can add methods to..

    [[NSNumber numberWithInt: 10] timesDo: ^() { NSLog(@"I want my brain cells back C!"); }];

  51. eike

    Using properties for type conversion.

    In some project back than, we had to cope with some weird representation of types.
    It was dates represented as 8bit values for year/month/day
    and some other weird stuff.

    I did use properties to convert the underlying data
    to more usable types (like NSDate or such)

    It worked out quite nice.
    I was able to shim and hide the bad old structure.

    I’m a big fan of properties.
    Please read the Eiffel Book.

    Accessing a property by read should never change the public state of the object.
    Acessing a property by write is a different story.

    I have my personal trail with the compiler team,
    I’d like to declare properties readonly to the outside,
    while redeclaring them read/write inside my implementation.
    This is not yet possible.

    I believe properties are a very good thing.

  52. Mart

    I’m not used to posting regarding languages, but I’d like to comment regarding:

    “When we see the invocation of that method with dot-notation, all we see is:
    int x = foo.value;

    What does that mean? Are we getting the value field out of the structure object foo? Are we executing a simple method that returns a value?”

    I’m coming from C#, which is simple and hence open to ambiguity. The question “What does that mean?” can be largely eliminated with naming standards. Method names begin with upper-case and, at least when I’m coding, they tend to contain a verb.

    If we consider that a programming language consists of syntax and conventions, then criticism of dot notation for not working well with objective-C practices seems a little redundant.

  53. GE-MU Systems

    Hi there ^_^,

    thanks for this insightful article.
    I am a big believer in explicit and strict notations, so I am with you almost 100%.

    One question though…
    How can I still use the very convenient foo++ without dot-notation?

    Do I have to use [obj setFoo:[obj foo]+1]; ??

    Thanks in advance!!

  54. Mark Dalrymple

    Yep! You’d have to explicitly get the previous value, add one, and then turn around and set the value.

  55. jhhl

    I’m on-and-off about dot notation, the same as I am with Interface Builder: it’s a feature that makes some projects easier, others more confusing. Remember the BOTH [] and . are syntactic sugar for objc_msgsend!
    Chiming in other issues raised: indeed, it’s VERY confusing that you think you have initialized structures mentioned in a .xib file when you created the structure but in fact, that doesn’t happen until its view is referenced (which, in the officially condoned “hide what you are doing” object philosophy, could be anytime).
    and view.frame is not an object, but a CGRect struct, which is why dot notation there is especially confusing!

  56. Chuck Wolber

    I do not think the assertion to never use dot notation is well supported here.

    This article appears to treat compiler errors as a serious issue. Sorry, but generating a compiler error is a reasonable instruction to the developer. This is essentially the basis for generics – pushing more of the debugging burden on to the compiler rather than ad-hoc testing. Purists will no doubt take exception to generics (and strong typing, forced exception handling, etc), just as old school systems administrators took exception to package based systems management. Their reasons were valid, but in the long run, the job just got too complicated to do without tools. The purist’s doom and gloom promises on those topics never really came to fruition and the pragmatists won.

    Another criticism is that dot notation hides what might be a copy or what could be a retained variable. At the time this article was written, this would have been a decent argument. Now that we have ARC, that argument is irrelevant.

    I think the “intent of code” argument is the only one that holds any real weight. It is indeed important to understand intent, but “never use dot notation” because it may make intent ambiguous falls a little flat. I think a better approach may be to write an updated article pointing out the dangers and pitfalls of dot notation, and teaches the developer how to use it correctly (sorry, it is not going away).

    In other words, sometimes embedding a method within a string of dot syntax may make sense, other times it may not.

    If you insist on ideological purity, then by all means stick with the pre-2.0 world. If you want to live in reality, understand that the usage of dot notation is a bit more nuanced than your article describes.

  57. Dr. Curl

    Our guiding principle here should be: KISS.

    Our mental faculties are already overburdened with information overflow.

    Listen to the man! He knows what he is doing.

  58. Sean McGuffee

    Thanks for the useful info. I have been somewhat aware of some of these issues, but I didn’t realize the details of a lot of it before. I just knew something was weird sometimes. I got to the point where I had started using Objective-C++ with C++ and had an Objecive-C++ object containing a pointer to another Objective-C++ object and a pointer to a C++ object. I could use a . to access the Objective-C++ object pointer’s members but had to use -> to access the C++ object pointer’s members. I was very confused until I read your post. Now I get it. How did I get three years into wasting time with dot operators and never realize they weren’t accessing members of structures? I really don’t know if Apple’s documentation talked about this and I just didn’t remember, or if they didn’t mention it. Whatever the case is, it’s a shame that it exists. I dislike it when people who have silly ideas mess with frameworks that competent people work with.

    I disagree with one statement though: “If one language solved all problems, everyone would use that language.” Maybe there is a problem that C++ can’t solve, but I can’t find it. It’s a shame to me that mac has to convolute all of their operating systems with Objective-C. It might be simple in some ways, but it’s a nightmare in all reality. I’m not sure how much of that has been caused by dot notation, but in general, the only reason Objective-C is used is not because it solves any problems C++ can’t solve. It’s because Mac made a bad decision to invest time and frameworks in a poor language. I wish Mac could just port all their frameworks to C++ and get rid of Objective-C altogether.

  59. Paul Chapman

    Thank you @Sean for a steaming load of McGuffee. Does the world really need _another_ post saying “my favorite language is better (read: more familiar to me) than ObjC”??

    I’ll give you this, I believe you are correct in saying C++ can solve everything ObjC can solve. However all solutions are **not** equally meritorious. They differ greatly in maintainability, brevity, clarity, readability, reusability and elegance to name a few.

    Each language encourages a certain kind of solution and thinking. ObjC is particularly good at encouraging loose coupling and IMHO does a better job of runtime dynamicism than C++ (disclaimer: I know every C++ guy/gal has a 3rd party library to shoehorn “something extra” into their favorite language, but for arguments sake I’ll stick to the mainstream).

    I find ObjC has an elegance and power all its own, and would hardly say “Mac made a bad decision … in a poor language” (FYI – “Mac” is not another name for Apple).

    As much as a beginner or recent convert to ObjC may find the language unwelcoming, every advanced language has its learning curve.

    FWIW: I agree with Joe’s (OP) comments about not using dot syntax to the extent that it’s easier for beginners. But consenting adults who know ObjC and undertand the difference will benefit from the code brevity it provides.

  60. Paul

    Bottom line: 3 years after this original blog post, the final paragraph of Paul Chapman’s post above mine, sums up the situation perfectly.

    Don’t use the dot notation until you are comfortable with the language.

  61. sunjen

    Sorry but dot notation rules!

  62. shipra

    Hello all,I am new and I would like to ask that what are the benefits of sql training,What all topics should be covered in it?
    And has anyone studied from this course http://www.wiziq.com/course/2118-learn-how-to-program-in-c-language of C tutorial online?? or tell me any other guidance…
    would really appreciate help

  63. Marc


    [obj takeDrinkOfLiquid:water whileDoingCartwheel:YES];
    We know exactly what that means

    I have no idea what that means and neither do millions of non-Cocoa developers. Is water a parameter, a class, an object? However, we all know what this obj.doThis(withThis); means.

    If you argue for code consistency (a valid argument within project teams) then the language must remain immutable and not evolve. If you want to reach a new audience you have to accept that bracket notation is an arbitrary convention like [param1|param2]<-method(){*obj} which is only readable to those already enlightened. In today's multi-platform, multi-language world we would do well to harmonise syntax and not innovate for the sake of being novel.

  64. martijn.s@gmail.com

    BULLSHIT !!

    when you see foo.value, u perfectly know what happens !

    if the getValue method opens a network connection etc, it should have another name !
    like

    [foo getValueFromOtherComputer];

    admit it, you are just being conservative.

  65. occular

    I don’t think dot notation is confusing at all. If you follow the usual principles: use dot for accessing properties, brackets for behaviour — it’s not confusing.

  66. vokus

    As a C# programmer, and a newbie to Obj-C, a dot notation is a salvation for me. Those brackets seems hard to understand and it is really much much harder to understand such written code. On the other hand dot notation is familiar for me from other languages and i can’t see where from all this hesitation comes. It is more intuitive and natural to use dot instead of brackets. I see a lot of effort in this post, but either way, i think that it is important to teach students to use notation which is supported by Apple. It make no sence not to. And legacy code shouldn’t be a reason at any case.

  67. Cong Liu

    http://blog.bignerdranch.com/83-83/
    “someView.frame.size.width = 30;”
    “Very straightforward, we’re setting the width of a view’s frame to 30 pixels.”

    Not “30 pixels”, but 30 points.

Leave a Comment

Join the discussion. Do not worry, your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>