In Which I Embrace Dot Notation …

September 17, 2013 — 24 Comments
Dot notation is okay

Or “How I Learned to Stop Worrying and Love Dot Notation”

I’ve been a staunch opponent of dot notation. I saw it as obscuring messaging, and encouraging programmers to violate the Law of Demeter through chained dots. I went so far as to characterize dot notation as an Objective-C code smell.

So it may surprise you to learn that I’ve recently adopted dot notation in my code! Here’s how it happened… 

Before I switched

I had two coding habits that struck some of you as peculiar:

  • Given a property, I preferred to access it through its backing ivar.
  • And of course, I didn’t use dot notation.

Some say, “Always use self-dot to access properties.” I didn’t agree, because if customized the setter or getter, it was easy to switch. No big deal. And since I didn’t want to use dots, calling

[[self prop] doSomething];

seemed excessive when I could simply do

[_prop doSomething];

KVO leads to properties

But then Eric Baker made that screencast of TDD using ReactiveCocoa. He took my MVC TDD screencast in a different direction. Instead of having the model post notifications when it changed, he turned much of my code into boilerplate, replaced by ReactiveCocoa.

I may try using ReactiveCocoa for a project, just to learn more. But here’s the key: ReactiveCocoa’s style of functional reactive programming depends on key-value observation (KVO).

The main reason I’ve preferred notifications over KVO is that I like using a separate methods to handle different aspects of the model changing. In KVO, all observing goes to a single method which then has to handle dispatching according to the changed aspect.

But what I didn’t know was that direct ivar manipulation doesn’t trigger KVO. If you want KVO, a class has to manipulate its own properties using the setters. So my direct ivar manipulation was effectively preventing anyone else from using KVO on my classes.

That’s no good. If you’re going to use one of my classes, I don’t want to cut you off from a programming tool just because I happen to code in a certain way.

Properties leads to self-dot

So “use your own setters” it is. And I’d rather not code one style to set a value, while using a different style to get a value. “Use your own getters” follows pretty naturally.

But eww, I don’t like

[[self prop] doSomething];

Suddenly I saw that “use your own properties” meant life would be cleaner if I adopted self-dot:

[self.prop doSomething];

And if I’m going to use self-dot… well, I may as well surrender.

Readability for the win

Dot notation is easier on the eyes. I’ve always admitted that. What I failed to realize before is that it isn’t just a matter of “aesthetics.” It’s more readable. And readability is super-important.

Somewhat related to this: dot notation is mainstream. By opposing it, I was going against the flow. I knew that, but it made me uncomfortable to make a screencast only to have people comment, “Why are you  directly accessing ivars?” So by adopting dot notation, I hope my code will be less distracting, so that you can focus on the principles I’m trying to show and not go all SQUIRREL!

Dot notation: still watchful for LoD

I still keep a weather eye on the number of dots, staying sensitive to the Law of Demeter. Chained dots still smell of Inappropriate Intimacy. So more than one dot (where self-dot doesn’t count) makes me question why fiddling around with a property’s property is any of the code’s business. But that’s probably a topic for another day…

So there you have it. Dots, yay.

What about you: have you ever switched sides in a coding holy war?

Photo by Arild Storaas (license)

Jon Reid

Posts Twitter Facebook Google+

I'm passionate about not just improving our code, but improving the way we code.

24 responses to In Which I Embrace Dot Notation …

  1. I have a round trip story with early returns :). I was using early returns always, then I stopped due to company coding conventions and start liking it, but later I decide to use them in cases where it makes my code more clear. Readability wins.

    Another one I have is about testing constructors. When I started TDDing I was always testing that the objects I was injecting in the initializer are set (I tend to use read only properties for the things I inject in the constructor) as well as the constructor throwing an exception when one of the parameters is nil(with STAssertThrows).

    Later I found that writing and maintaing those tests is too much work so now – specially when you add or remove one parameter to a constructor, as this in ObjC implies changing its name, and Xcode is not making that easy – I only test that the properties are set but not the exception throwing. I still use NSParameterAssert(injectedParameter != nil) for every constructor argument, but the work of writing and maintaining those tests is not worth IMO.

    • Emilio, I find it pretty easy to add/remove parameters from initializers by using AppCode and its “change signature” refactoring. When a parameter is added, all callers are adjusted and pass in nil.

  2. Nice post Jon, I just want to add something related to “I still keep a weather eye on the number of dots, staying sensitive to the Law of Demeter.”
    This post helped me a lot to understand when I’m really violating the law of Demeter. Also Martin Fowler makes a interesting commentary in this post that he would prefer to call it suggestion of Demeter, haha.

    • Raphael, thanks for those links. The statement “The Law of Demeter Is Not A Dot Counting Exercise” really only applies to interfaces that return self, so that methods can be chained. And that doesn’t apply in Objective-C, where such builder methods would be true methods, not properties, so most people would avoid dots anyway. Martin Fowler on the other hand is pretty awesome and I take what he says seriously. So I’m less concerned about chained dots that flow across Apple’s framework objects. But if one of my classes is in the mix… well, that strikes me as a smell that my class isn’t quite right.

  3. Jon, do you use properties for your private ivars too? I have recently been using properties for everything except for private ivars which probably are not candidates to be KVObserved. I am using this convention to distinguish between:

    public property access
    -(void) abc
    self.publicProperty = x;

    public property in an accessor/mutator or init/dealloc
    -(int) publicProperty
    return _publicProperty; // we know this is a property because leading _

    private ivar with no leading ‘_’
    -(void) def
    privateIVar = 20; // we know this is private and not a property because no leading _
    I haven’t yet decided whether this is valuable.

  4. I recently read GitHub’s Objective-C style guide, which it’s weird they actually recommends people to use dot syntax for invoking methods.

    Use dot-syntax when invoking idempotent methods, including setters and class methods (like NSFileManager.defaultManager).

    I don’t like this at all, dot syntax should be used for accessing property only. I don’t want to abuse dot syntax just for making codes a little bit concise.

    • This coding style is pretty interesting because it goes against everyone’s style! The goal is not to make code more concise, but to clearly communicate what is idempotent and what isn’t.

  5. Like you, Jon, I originally disliked the dot notation. I thought it introduced an ugly inconsistency between dots and square brackets for little benefit. However, about a year ago, I read an old article by Chris Hanson ( that totally changed my thinking.

    As Chris suggested, I had always seen dot notation as an alternate syntax for invoking methods. However, that short article changed the way I think about them, and I now use properties exactly as he suggests… as a way of signifying intent to the consumers of my classes.


    • Craig,
      I’d seen Chris’s article before, and I didn’t care for it at the time. Maybe I was a Smalltalk curmudgeon: “Properties? We don’t need no stinking properties!”
      Thanks for the link, I’m sure folks will find it interesting.

  6. I was just reading your “Dot Notation in Objective-C: 100% Pure Evil” post which made good points but for the most part I disagreed with. It’s good to see we’re in the same camp now.

    I just found your blog. Keep on keeping on!

    • Jay, I think the important question is not so much “Which camp are you in?” but “What are your reasons?” Who knows, even Dijkstra may have snuck in a GOTO once, because engineering is often about choosing between imperfect alternatives.

  7. I feel there’s a lot of pedagogical value in “[self setValue:[self value]+1]” (let’s not get into “self.value++”!). Then, once that value has been extracted an internalized, I prefer the readability value of “self.value+=1″. I have been opposed to “_value+=1″ for quite a while now.

    The two benefits I see of explicit square-bracketed message sending are A: there is no question that message sending is involved or how many messages are involved, and B: it forces realization that incrementing is a multi (3) stage process… load, calculate, and store. For students that still don’t get why “x=1; y=x+x; y=2;” will result in x having a value of 1, raising awareness of loads and stores helps clear out a lot of confusion.

    Once I trust someone understands what’s going on under the hood enough, I’m happy to see “self.value += 1″, since I feel it communicates intent more clearly. Then again, [self incrementValue: 1] is easier on my eyes, but at the cost of non-standardness and having to create extra methods.

    As for “_value += 1″, though, good riddance! Direct access of the *back*ing variable increases debugging difficulties, risks obscuring scope/ownership of the variable (mitigated by _naming conventions and/or IDE coloration assistance), couples the code to a particular implementation, and loses out on any freebies (e.g. memory management, KVO) provided by the accessors. I’ve had students prefix all their backing variables with “_DNU_” (and, for repeated transgressions, “_Do_Not_Use_”) as an unsubtle reminder to funnel access through accessors.

    On a related note, I was quite delighted when it became possible to declare state in the implementation rather than the interface of a class. I’m also a big fan of @property.

    • I definitely see value in avoiding dots for pedagogy, at first. Objective-C’s runtime supporting true message passing is one of its greatest strengths, compared to other OO languages which invoke functions instead of passing messages.

  8. Hi Jon,

    I just got used to accessing property using as ivars “_property” :) … feeling like I’m simplifying my code sooo much and looking down on all those “self.” developers (who insist for “no reason” on the “self.” :)

    Right now I also plan to learn all about keypath observation, since I think it a good way to do most, how to say, “economic” and efficient communication between model and controller (in certain cases) … so I must say your article provoked me into changing my love for “_property”.

  9. Well. I used to use Vim years ago but now I use IDE (YAY!) for daily coding and Emacs (oops) for scripting. Does that count “switching sides in a holy war”? :p

    Holy wars are evil anyway…

  10. Maybe i’ve got something wrong and this kind of for Insiders … but … Eric Smith?

  11. I’ve just recently switched sides in the dot notation war, mostly due to Xcode 5′s often frustrating support for auto completing square brackets.

    It is just easier and faster for me to type the dots than to interrupt my flow by having to manually correct Xcode’s often badly placed opening square bracket. TextMate was/is a lot smarter about autocompletion of message brackets. I probably should be using it more, but I’m lazy.

    So really, laziness and Xcode editor irritation has finally worn me down. Xcode 5 doesn’t mess up dot notation nearly as much as it does square brackets. I do double-check headers to make sure I’m only using dots to access declared properties. Using dots only for property access is a pragmatic rationalization that I can get behind.

  12. Hello Jon,

    I’ve just found your blog today – I’m looking forward to find out out much I didn’t know! :)

    “Dot notation is easier on the eyes. I’ve always admitted that. What I failed to realize before is that it isn’t just a matter of “aesthetics.” It’s more readable. And readability is super-important.”

    This reminded me of something I was told (many!) years ago by my boss, “A computer program is primarily a document for a human being”.

    Wise words that I try to keep in mind as I’m coding.

    As a relative newbie at Cocoa I’ve always stuck with dot for properties and methods for, well, methods. I suppose following Apple’s guidelines seemed wise in the absence of conflicting advice.

    • Stephen, welcome to Cocoa!

      Uncle Bob puts it this way: readability is more important than correctness. (Because if it’s readable, you can fix it. But if not, good luck making any changes.)

  13. Christopher Schardt February 7, 2014 at 3:46 pm

    I too have come around to using dots…. a bit! I use them now, but only for getters. I don’t use them for setters because:
    1) self.item = self.someMethodThatCreatesAnItem hides an unknown amount of functionality. [self setItem:...] makes it much clearer (to me) that self is getting changed.
    2) Often, one has not only the [setItem:] method but also [setItem:withContext:] I find it icky to be able to write
    self.item = item
    in some cases, but in other cases be required to use this syntax:
    [self setItem:item withContext:context]
    Therefore, I always use [set...] syntax. This also makes it completely clear what to search for if I’m looking for all instances of calling the setter. I know I can search for “setItem:” and find every one.

    Very often I think, “If ONLY the creators of Objective-C could have just been happy with the ()-based method-calling syntax of C”.

    • Christopher, I’ve seen a “dots for getters only” style used by one instructor at Big Nerd Ranch. (And he did succeed in getting Aaron Hillegass’s okay for this.) So you’re in good company!

      As for the “method-calling syntax of C”, Objective-C’s OOP roots lie in Smalltalk. Besides that, I see huge advantages in named parameters as opposed to something(foo, bar, baz, qux, quux).

Leave a Reply


Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> 

Have you Subscribed yet? Don't miss a post!