.st0{fill:#FFFFFF;}

In Which I Embrace Dot Notation … 

 September 17, 2013

by Jon Reid

28 COMMENTS

Dot notation is okay, after all.

There, I said it.

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 Lead 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.

Dot Notation: Still Watchful for Law of Demeter

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? Leave a comment below.

Jon Reid

About the author

Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Extreme Programming, including unit testing, test-driven development (TDD), and refactoring. Programming became fun again! I've now been doing TDD in Apple environments for 20 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy. Now a coach with Industrial Logic!

  • 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.

  • 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.” http://haacked.com/archive/2009/07/13/law-of-demeter-dot-counting.aspx
    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 http://martinfowler.com/articles/mocksArentStubs.html 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.

  • 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.

  • 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.

  • 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 (http://eschatologist.net/blog/?p=226) 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

    • 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.

  • 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.

  • 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.

  • 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”.

  • 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…

  • 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.

  • 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.)

  • 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).

  • I often tend to try to adapt to the situation I’m in à la “When in Rome” style.

    So when I started using the Mac, I left it with CMD+C/CMD+V instead of switching it to CTRL.

    In the case of this one, I came from a Java/C# background, so was very at home with Dot-syntax. As such, when I was taught about it, I used it for properties, but not for other methods.

    Though, when Swift came out entirely using Dot-Notation, I was in quite a happy place.

  • You haven’t fully embraced dot notation until you start writing

    [[self prop] doSomething];

    as

    self.prop.doSomething;

    and if that looks weird to you, then maybe there’s something wrong with dot notation.

    Have you ever gotten a compiler warning for the perfectly reasonable looking:

    self.view.frame.size.height += 12;

    ? Then maybe there’s something wrong with dot notation.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >