Archive for the ‘Musings’ Category

Enter the Python: Peeking at a language

Last week, I wrote about how I set up Xcode to run Python. It’s been working great. Xcode may not be everyone’s cup of tea, but I love it. Syntax highlighting, familiar keybindings, symbol completion. I couldn’t be happier. A lot of people pushed me to use Pycharm community edition, but while I’ve installed it and tried it a few times, I keep going back to Xcode. Warts and all.

I haven’t logged many hours in Python but it’s been a fascinating language experience. Let me go all metaphor on you. Way back in the 90’s there was this show called “Sliders“, about a bunch of people moving between parallel worlds. Almost everything was the same from world to world — normal humans, trees, buildings, whatever — but there were always fundamental differences in the culture and the people that always reminded you that you weren’t home.

Python is the Sliders version of Swift, the one where Chris Lattner was never born. Everything is eerily familiar and nothing is quite right. Where are my value types? My generics? My type extensions. Let me throw out another metaphor — one that will probably resonate with even fewer people: Python is the language version of the Nethack Rogue Level, where you enter “what seems to be an older, more primitive world.” It’s all familiar. Nothing is exactly the same.

This morning, I attempted to extend a type. I’m working with Anki’s Cozmo robot SDK, which is written for Python 3.5.1 or later. I’m trying to reconfigure many of the basic calls into more appropriate chunks suitable for teaching kids some programming basics.

Instead of focusing on asynchronous callbacks and exceptions, I want to provide really simple blocks that extend the robot type API in a way that hides nearly all the implementation details. I’m trying to build, in a way, a Python version of Swift Playgrounds but with a real robot. (And it’s going well, but more about that in another post.)

What I found was that Python really doesn’t want to extend types. You can subclass. You can compose. But so far, I haven’t found a way to add an extension that services an existing type. When I asked around, the Python gurus on freenode recommended I stop worrying about polluting the global namespace and embrace freestanding functions as needed.

Oh, my delicate Swift sensibilities! Adding global functions and constants? Cluttering the global namespace? I find myself clinging to Swift conventions. I create enumerations and type my arguments:

class Direction(IntEnum):
    '''Permitted driving directions.'''
    forward = 1
    backward = -1

def drive(robot: cozmo.robot.Robot, 
    direction: Direction = Direction.forward): ...

The Cozmo SDK defines its constants like this:

LEFT = 1
TOP = 4

I don’t think I’m in Swift-land anymore.

A lot of the things I like most about Python appear to be fairly new, like that ability to type arguments. I’m assured by some Pythonistas that this is almost entirely syntactic sugar, and there appears to be no type-checking, inference, or casting applied to calls.

I thought I would really hate the indentation-based scoping but I don’t. It’s easy to use (start a scope with a colon, indent 4 spaces for that scope). It reads well. It’s clean. Non-braced scoping ended up being a complete non-issue for me, and I mildly admire its clean look.

I’m less excited by Python’s take on structured documentation. The standard is outlined in PEP-257. Unlike Apple’s Swift Documentation Markup, Python markup doesn’t seem to support specific in-line tool use in addition to document generation. I’m sensitive to how much better Swift creates a structured system for detailing parameters, error conditions, return types, and descriptions, and how it scales from types to functions and methods to individual instances and provides Xcode integration.

So much in Python is very similar to Swift but with a slight twist to it. Closures? Lambdas are in there. Mapping? That’s there too. Partial application? Seems to be. Most times that I reach for a tool in my existing proficiencies, I can usually find a Python equivalent such as list comprehension, which is basically mapping across sequences and collections.

I’m sorely missing my value types. One of the first things I did when trying to work through some tutorials was to try to create a skeleton dictionary rather than type out full dictionaries for each instance. I quickly learned Python uses reference types:

# the original dict was more complicated
studentDict = {"name" : "", "tests" : []} 

joe = studentDict # create joe
joe["name"] = "joe"
bob = studentDict # create bob
bob["name"] = "bob"

# reference type
print(joe) # {'tests': [], 'name': 'bob'}
print(bob) # {'tests': [], 'name': 'bob'}


In any case, I’m still really really new to the language given my full-court-press on finishing Swift Style. As much as I wish I were writing this code in Swift, I’m glad that I have the opportunity to explore Python and hope I get to spend some time with Scala in the near future. This project is offering me a lot of valuable insights about where Swift came from and increased appreciation for the work the core Swift team put in to give us the language we have now.

Swift Holy War: Comments are not an Anti-pattern

Got into a debate yesterday about this write-up by developer Andrew Warner. His “Beware the Siren Song of Comments” suggests that developers delude themselves because comments detract from code quality:

Comments decay. They aren’t compiled, and they’ll never get executed at runtime. If they become out of date or incorrect, no test is going to fail and no user is going to complain. Programmers work around them out of fear that “somebody might need this comment or it might provide some value in the future”, pushing them along far after they’re useful (if you can even argue that they were useful in the first place).

His recommendation?

[Y]ou don’t have any excuse to write comments. Give these methods a try, and I promise you’ll have a cleaner codebase that’s easier to maintain.

I don’t claim that comments should counterbalance bad design decisions like poor naming or flawed algorithms. I do believe they play an important role in good coding practices — whether or not your code is meant strictly for internal use or to be consumed as APIs.

As I discussed on this blog a few weeks ago, there’s a big difference between the you writing code and “future you”, your team, and anyone else reading code. Here’s what I have to say about commenting in Swift Style:

Comment, comment, comment and while you’re at it, write tests. Tests can save you the whole “What I was doing here?” because you can just look at what is broken and what you expected to work.” It’s better to write less code and make up that time by explaining the code you did write better.

Sure, it helps to leave in a “TODO:” where it counts (“the performance is really bad here”) but while you’re at it, try to leave a few ideas about what exactly is going wrong, and what hypotheses you have rolling around your soon-to-be-extinct neurons. Past you understood things. Future you is clueless.

It always costs less to fix things in the past because you’ve invested in uploading the full design into your brain. Re-upping that design and getting back up to speed involves huge penalties.

Comments can explain the non-obvious, the tricky, or the counter-intuitive to a reader: This is intentional. This thing affects that thing. This data is not validated at this stage. Responsibility for this process now passes to this delegate. Comments enable you to establish what your assumptions are at which points in code and they allow you to comment on design qualities.

Comments create a record of intent. They may mention approaches that were tried and why they were abandoned. They may discuss how design decisions came to be — what paths were explored and why some of those paths weren’t chosen in the end.

Comments allow you to colocate thoughts with the code they refer to. Commit messages are helpful but I don’t think a commit message is  the proper place to document workarounds or unexpected behavior. Plus version control history may not travel with source code, if the code is reused in another project.

Comments provide a bread crumb trail of design decisions that aren’t kept in working memory and cannot be intuited just from reading code or scanning tests. Unexpected complexity is one of the things you’ll want to comment about. In fact, commenting on the unexpected is important because the alternative is essentially a bug.

Structured comments add another layer of utility, supporting API consumption. Markup allows these special comments to automatically convert into highly formatted local documentation supporting another set of readers beyond code review, debugging, maintenance, and enhancement.

Comments don’t just paper over bad design and coding. They document a process of making code right, supporting future reading and modification. Good comments reduce the mental effort needed by readers each time they review your source, enabling them to focus more on specific tasks like “how to I add this feature” rather than “what the hell was going on here”. While good code can at times be “self documenting”, that doesn’t mean it always is (or even usually is) self documenting.

As stepping stones to “past you”, good comments document what you were thinking and why you did things the way you did. Your past design decisions should never be a mystery or a burden placed before future readers of your code no matter how brilliant or insightful you expect them to be.

Reconciling Past-You with Future-You

It’s a basic truth in programming. When you get interrupted before coming to a really good stopping point, you are screwed. Life happens. And reality is cold and harsh.

Sure you intend to comment about what needs fixing and where you left off, but past you always provides less reminding than future you desperately needs. Future you can be really dense.

The very worst moments happen when you break off in the middle of refactoring. That grand design you had in your head, the one where every piece fit together like a stunning mosaic? It’s gone. Duct tape, band aids, and a bit of WD-40 are all you have to look forward to.

Past you and future you are never friends.

If you’ve ever written a comment like “// The methods in this class probably don't work the way you'd expect based on their name“, you know what I’m talking about.

Never underestimate future you’s stupidity. Comment, comment, comment and while you’re at it, write tests. Tests can save you the whole “What I was doing here?” because you can just look at what is broken and what you expected to work.

It’s better to write less code and make up that time by explaining the code you did write better.

Sure, it helps to leave in a “TODO:” where it counts (“the performance is really bad here”) but while you’re at it, try to leave a few ideas about what exactly is going wrong, and what hypotheses you have rolling around your soon-to-be-extinct neurons. Past you understood things. Future you is clueless.

It always costs less to fix things in the past because you’ve invested in uploading the full design into your brain. Re-upping that design and getting back up to speed involves huge penalties.

Remember these core lessons:

  • Future you is thick as a plank.
  • Comment as if you are writing for a particularly dimwitted stranger, especially when that stranger is you.
  • Build tests. Add examples. Fill in structured document fields. The more you comment now, the less grief you’ll experience in the future.
  • Past you is a total jerk.

When did Ikea ditch the sunshine, rainbows, and unicorns?

The new Ikea catalog arrived yesterday. Is it me or have they turned over their design to some crazed Swedish goth intern? My new catalog feels more Hitchcock and “Vogue Editorial” than “Affordable purchases for people who wish they could fix their out-of-control lives.”

Ikea’s gone from cute girls in a colorful apartment (top, 2015) to psychotic butcher knives that think they’re actually vegetables (check out that shadow) and this recurring weird backdrop thing, which makes me think they couldn’t afford an editor to crop the photos properly (bottom, 2016).IMG_1527

Suddenly, they’ve transitioned from simple product images inspiring you to simplify and organize  your life to a kind of nightmare clutter scenario where all reason has fled and you apparently must buy every product available from the company and store them in the open without drawers, cupboard doors, or any break in sanity.


Look at that poor woman standing at that kitchen island. Her entire body communicates the tenseness from barely having a spare inch of counter space, banging her knees against all the junk on the two shelves, the shame of putting your dishes out for public viewing. Inside, she’s screaming “I will never get my life under control and it’s all IKEA’s fault! For just $499!”

(By the way, I love the LED light at the middle of the right page of the 2015 catalog. Mine is black, not red, and it’s perfect between my two computer monitors. Folds up out of the way when not in use.)


Apparently 2016 is the year of dark spaces, drawn blinds, and Carmen cosplay. You can pretend to die of consumption in the gloomy shadows of your living room, while dressed in red and practicing ballroom in the  (perhaps) 2 square meters of space between couches.

And can you think of anything scarier than your sofa actually being your home. Last year, a beautiful, open plan living room, with a family happily getting work done on the laptop and reading to a kid. They seem happy, their plants seem happy, the lightness and brightness no doubt makes them feel free and open and relaxed. Compare that to this year.IMG_1525

No, Ikea, a sofa is not the home. And who are all those strange people who wandered into this poor woman’s life just to stare at and harass her?

Here’s Elsa. Elsa thought she’d have a lovely relaxing time, putting up her feet before picking up the kids and stopping by an organic locally sourced market for take out to eat while perched on a variety of ottomans and sleeper couches.

Who would ever have expected an entire gang from Twitter to take up residence on the other side of her monster sofa, laughing at her, mocking her, and critiquing her lounging style. That gang of four sure think Elsa is a hoot. And all at the same time, creepy Helmut from down the road just stares at Elsa with unrequited longing. I think perhaps he’s humming ska songs from the 1980s to her.

Poor Elsa. This is what comes of living in the middle of a photographic studio, without doors to keep out strangers, no storage for clothing, a ragtag group of floating sofas for the young ones to sleep upon, and three mysterious remote controls to remind her a time when she had a real house to call home.

Oh Ikea. It’s time to say goodbye to 2015, with its misty bright hopes for a world of knotty pine. 2016 has arrived with its dark bleak dystopian furniture and a bookshelf that looks like an insurance liability court case ready to happen.


(As a side note, I had no idea that sleeper sofas crept out of their homes while we were at work to embrace that secret 24-hour life. It must get crowded at the bowling alley and at the local microbrewery when affordable furniture sits around, drinking lager, and sharing the stories you thought were kept secret.)

The names of things

Last night, someone was asking what you call the things created by types. My take on the subject is this: Classes, structures, and enumerations are constructs. You create new instances by calling a constructor, even when building things that aren’t reference types.

I avoid calling reference types “objects”. I stick with instances, following the Swift Programming Language’s lead, e.g. “Use the init?(rawValue:) initializer to make an instance of an enumeration from a raw value.” and “Create an instance of a class by putting parentheses after the class name.”

A big naming challenge derives from what do you call the thing that stores a value. The Swift Programming Language has this to say: “Use let to make a constant and var to make a variable”, which is not at all helpful because you end up saying “Declare a variable or constant”, “use the variable or constant as a parameter to the function”, etc, etc.

While constants and variables are “bound symbols”, “value bindings”, or just “bindings”, those are hard names to use in writing. “Create a value binding of 5” doesn’t communicate the way “create a new variable or constant and set its value to 5” does.

This is why, I prefer to stick with variable to describe both in any indeterminate situation. Constants are really immutable variables, egregious oxymoron and all. And, as Joe Groff points out, constants are still variables according to the mathematical meaning of the term.  It’s not a great solution but nearly everyone gets it.

So unless you’re going for precision, go ahead and declare a variable to store that value. If you don’t or won’t mutate it, the compiler will remind you to mark it as a constant. Long live “let variables“. It may not be technically precise but it does communicate expressively.


Trailing commas, open source, and community participation

The wave of support, kind words, and tweets after the rejection of SE-0084, which introduced support for trailing commas in declarations and at call sites, has been very kind but rather misses the point of open sourcing the Swift language.

While Apple’s Joe Groff provided a strong voice of support for SE-0084, there were few concurring list members willing to speak up for it.

John Siracusa wrote, “Having used, more or less continuously for my 20 years as a professional programmer, both a language that allows trailing commas and one that does not, I come down pretty strongly on the side of allowing trailing commas (for all the reasons already stated in this thread). If it means requiring a newline after the last comma to make some people feel better about it, so be it.”

Brent Royal-Gordon also voted in favor, “I was skeptical of this until a week or two ago, when I had some code where I ended up commenting out certain parameters. Removing the now-trailing commas was an inconvenience. So, +1 from me.”

The remaining community votes were almost entirely negative, with a special award for honesty for Chris Lattner, “I personally find that style repulsive.” In this light, comparisons to Perl and C that show up after the review period has ended don’t add support or change the outcome.

Unless you’re willing to participate in the Swift Evolution process and speak up for or against proposals, the outcomes may not reflect your specific development needs. The best arguments for or against a proposal are real world code, measurements of use in public and private libraries, and pragmatic use-cases that express why a proposal should be adopted or not. Swift language changes should fix real problems and must be demonstrated with real data.

The best evolution reviews include thoughtful analysis of how a change affects existing code bases, improves outcomes, and compares to other programming languages. They should analyze how the proposal fits with the specific feel and direction of the Swift language. A surprising quantity of review feedback ends up as “+1” or “-1”  one-liners, which don’t really help guide the evaluation of a proposal’s merits.

Evolution members are welcome to post their reviews publicly or to directly contact the review manager with private feedback. I have participated privately in a handful of reviews and publicly in others. I’ve abstained from reviewing many proposals (there are now over a hundred of them) when I had no strong feelings or no background to evaluate a topic.

Swift Evolution, as all open source projects, offers an imperfect process:

  • There is far too much on-list traffic to keep up with. It helps if you’re specifically dedicated to documenting the language and its process, which is an extreme outlier case.
  • Participants are self-selected and skew towards people who dedicate time to debating language design; that time must naturally trade off from work, spending time with family, watching TV, or engaging in other lifestyle activities and hobbies.
  • On-list consensus may not match the consensus in the wider developer community and there’s often quite a strong backlash against attempting to measure the temperature of that wider community.
  • If you think “best editor” wars are bad, you haven’t seen the bikeshedding over multi-line string grammar.

To be clear, Swift Evolution is not “design by committee” as some mass wave of crowd consensus. The Swift process was designed from the start to be both opinionated (“Swift is an opinionated language”) and  focused given the circumstances or community involvement. At this point, I can’t remember if Apple wrote this or I did, but “maintaining that coherent vision for something as complicated as a programming language requires both coordination and leadership.”

The ultimate responsibility for adopting changes lies with the Swift core team, which acts as Swift’s internal star chamber. The team establishes the strategic direction of Swift. Core team members initiate, participate in, and manage the public review of proposals and have the authority to accept or reject changes to Swift.

The majority of work and discussion take place on the highly-trafficked Swift Evolution mailing list. This list provides the platform to propose, discuss, and review ideas to improve the Swift language and standard library. There are few participation rules, mostly to do with adhering to a respectful code of conduct.

Using a mailing list establishes a public record of all proposed changes and their ensuing discussions. Participants can explore archives to determine whether a topic has already been discussed and/or voted on, and what the arguments for and against those changes were. The Swift Evolution archives are available at and

Having votes go against your preferences is part of the reality, and there are often some very good underlying reasons why some proposals go the way they do that are obvious on the larger scale than the smaller (to simplify the language, to enhance reliability, to obtain more accuracy, precision, and speed, because of the internal compiler limitations, etc.) The core team feedback at the end of the review period explains why each vote went the way it did.

That said, each proposal needs its champions. The process can be tedious and needs to be driven from a pitch through drafts, from pull request through review. Supporters should be available through the review process to answer questions, update text, offer code.

With Apple standing behind Swift, its impact is both large and loud. If you love coding and language design, there’s rarely an opportunity like this to become part of the process and help influence its outcome.

If I had my druthers: Swift 2.2, Swift 3.0, ABIs, etc

If I could wave a magic wand, I’d push Swift 3.0 out by a year or even better three years and fix Swift 2 as the standard App Store language (and for Linux, and upcoming Windows) exactly as is, barring a few tweaks and fixes over this time.

[tl;dr summary: Make big breaking changes later and once rather than sooner and multiple times. If a delay allows a single stable language transition, it is to be preferred. Aim for post-3.0 language updates to be additive not transformative.]

Swift 2.2 is a great language. It’s amazing to work in. It offers utility and concepts that Objective-C cannot provide. It pushes iOS and OS X development forward in an important and exciting way, affecting development not just on Apple platforms but wherever Swift touches. From first class structure and enumeration types to protocol oriented programming, Swift 2.2 delivers the goodies.

If you need just one compelling single example, take CGRect: Swift 2.2 lets you expand this essential structure with methods and properties that let you center on a zero origin, or scale and transform, or add math to combine instances. It’s so practically useful that going back to ObjC to work in geometry metaphysically hurts.

Swift 2.2 gets it right in so many ways, that it seems ridiculous to throw it away at the end of the year. A language this good should have a lifetime longer than 8 or 10 months. I’d be really happy if at the WWDC keynote, Tim Cook said, “We got it so right, we’re going to stick with Swift 2, let you build your code for long term use, and make sure the transition to Swift 3 will be perfect.”

The move to Swift 3.0 isn’t just going to be disruptive. It’s going to be traumatic. With its expansive renamification and redesigned core types and APIs, Swift 3 is going to be a tidal wave of retraining and refactoring. And with a list of objectives that didn’t quite make the cut, and a laundry list of of items that should have, Swift 3 just doesn’t have enough time or scope to be perfected.

So why not just push it back?  Let us devs use Swift 2.2, which is terrific, for a few more years and get Swift 3 right the first time?

It’s not as if Swift Evolution needs to be fast paced and hectic. The bikeshedding, the simple natural discussion overhead, the need to foster a courteous open source community means the natural speed of development has taken a huge hit.

These arbitrary “update every year” advances that Apple has bought into are more than a little ridiculous when it comes to firmware and OS updates; for languages it pushes beyond the practical.

Orson Welles promised that Paul Masson would sell no wine before its time. Apple should take a lesson from Welles and ship no language before the follow-up version has properly evolved.

I want to see Apple slow down, take some deep breaths, and seriously consider letting Swift 2.2 come into its own rather than cutting it down after a few months of use.

As it is, I am constantly having to answer “Is it time yet to switch to Swift?” As this breakneck development continues, I’ve been hesitant to recommend jumping aboard the Swift train for simple practical reasons.

I’d be far more confident with my advice if I could see a 2-3 year window with stable code that could benefit from Swift’s modern language features, and a payoff of investment in training and refactoring that won’t have to be re-addressed with each new beta and each new release.

To paraphrase a line from Aesop, slow and steady really does win the language race.

Like my posts? Consider buying a book or two or three. Thanks!

Dipping toes into coworking

As George RR Martin would have put it if his kids were in public school: Summer’s coming. (“A Song of Bored and Cranky”) This Summer, I plan to try to use some coworking spaces to get the heck out of the house and away from the kids for a couple of days a week.

So far, I’ve tried out “eat-working” (Starbucks, Panera, Einsteins), which really doesn’t offer the kind of long-term desk situation I’m looking for, “public-working” at the library, which had iffy chairs and tables and intermittent Internet, and (so far) one commercial day trial, which had great desks, horrible chairs, nice ambience, but a no-talking policy which meant I couldn’t conference, use my phone, or use Siri except by stepping outside. (And absolutely no way to turn up the iTunes volume and shout it out, shout it out loud…)

If you’ve coworked and have any recommendations for what I should be looking for in a good coworking space, please share. I’m not exactly looking for place recommendations (unless you have specific ones to mention) but more to put together a list for myself of what makes a good coworking environment so I can better evaluate what I”m looking at before committing to any monthly or longer contract. I’d appreciate any advice you have to offer.

I’m looking for something fairly local, inexpensive, with good business-level WiFi, comfortable business-level chairs and desks (I can bring in my own lumbar cushion and footstool if needed), safe area, clean bathrooms, nearby shops, a microwave, easy in-and-out, and  daylockers of some sort so I don’t have to carry absolutely everything in and out with me every time I hit the bathroom or go to lunch. I’d also like to be surrounded more by tech folk than marketing folk but I recognize that’s not going to be something I can control.

I will say that while I was remarkably productive on my days out, I was productive in all the wrong ways: I zoomed through my correspondence. I’m now set up beautifully with my calendar and with “Things“. I got nothing done on actual development or real writing work. And I did nothing that needed phones, such as making appointments or checking in on projects. I also found it really hard to take breaks, stretch, and just do the “wander and think” thing.

What kind of work opportunities do you reserve for outside your office? And how do you adapt your workflow to small screens (I have the new MBP with me), strange places, and ergonomic limits?

Thanks in advance for your thoughts.

Fast-tracking Swift reviews

I’d like to see Swift Evolution adopt a couple of styles of fast track reviews. Here’s how they would look.

STYLE ONE: Minor language enhancements AKA “Low hanging fruit”

It would help if the core team could add minor language enhancements without going through a formal proposal process with its normal review overhead. I have now been involved in several reviews that involved API changes that were otherwise unremarkable and primarily motivated by modernizing and style:

To this list, you could add:

Each of these proposals could have proceeded with a simple “any objections” sanity check discussion period rather than a more formal full review. As a another example (now unnecessary), consider the `dynamicType` keyword, which would have required a formal proposal to be modernized into Swift’s lowercase keyword standard. The hallmarks of these changes are:

  • They have limited impact
  • They increase language consistency
  • They are uncontroversial, offering simple, straightforward, and correct changes  that have already passed review in spirit, if not in letter
  • A preponderance of reviews are “+1” rather than in-depth discussions of why the proposal  should or should not be adopted.

I would recommend retaining a change document requirement for these proposals. This would be similar to a brief but formal proposal, that lays out the justification, detail design, and any associated background info for the change. Doing so would provide a historic record of the change and any notes from the team, and be in a form that would support the extraction of key details for use in release notes.

I do not know whether these would need to be grouped and numbered with the normal proposals or placed into their own numbering scheme.

STYLE TWO: Fast tracking viability

Once a draft has been discussed on-list and submitted as a pull request, I’d like to see a biweekly (or even once-a-month) Pull Request Review meeting from the core team where a review groups looks over the current pull-request queue and scores them: recommend closerecommend promoteneeds workdefer past 3.0. This approach:

  • Would offer closure to proposal authors who are otherwise unsure of the viability of their proposals
  • Naturally happens after a significant on-list discussion/pre-review period has already  taken place
  • Would allow the team to weed out proposals with significant issues before entering formal review
  • Would allow on-list reviews to give precedence to only those proposals that make sense both in the time context of Swift 3.0 and its overall design philosophy.

Swift is an opinionated language. This review style would introduce discernment and feedback slightly earlier in the process without stifling on-list discussion.

A few final thoughts

It is a given that Swift 3 is going to be the last opportunity to make large, code-breaking changes to the language. With that constraint, I’d like to see more time and effort go into improving Swift’s fundamentals. Any time, effort, and review that can be better spent getting collections and indices right rather than worrying about colons and casing is, in my opinion, worth a tradeoff in community control.

The natural tension between engagement and coherence requires a balance that serves the entire Swift community. Open evolution processes are, by nature, chaotic. Maintaining a coherent vision for something as complicated as Swift requires coordination and leadership.  That’s why the ultimate responsibility for adopting changes lies with the Swift core team, which establishes the strategic direction of Swift.

I hope by adopting these fast-track review styles that the Swift open source community can better focus on the big updates while making sure that the small details are attended to carefully and thoughtfully without overwhelming the process.

Swift Style: Are you a 4-denter?

Two space indentation seems to be the new craze. “Four space indentation? Are you mad, that’s nearly as bad as tabbing with eight?” is the meme of the moment. (Or, as established in Zoolander, “Two spaces? It’s so hot right now.”)

While two space indentation offers more horizontal space to work, four spaces continues to create an elegant sense of white-space and scope-based horizontal stepping that provides light and easy reading.

(I ignore the three space addicts in this discussion, while acknowledging they do exist. As Mike Ash puts it, “I think three spaces should be, ‘Do not approach. Retreat to a safe distance and call the police as soon as you’re clear.‘” Chris Lattner counters, “I think you under appreciate 3 space indent.  It looks the best, and conclusively settles the tabs vs spaces debate.” coughtrollcough1)

Like my previous colon discussion, Apple answers seem to vary by group. Apple docs, including the Swift Programming Language, consistently use four spaces, enabling clean examples that breathe:

Screen Shot 2016-03-31 at 9.00.40 AM

and the Standard Library group uses 2, following LLVM Coding Standards, which I find a bit claustrophobic. (Thanks, Greg!)

Screen Shot 2016-03-31 at 9.01.39 AM

So I went off to google. First up, I found a 1983 ACM paper by Richard Miara, Ben Schneiderman, and some others called “Program Indentation and Comprehensibility“, which sought to test whether 2-4 spaces were more ideal than 0 or 6 spaces. Unsurprisingly, this premise was born out by their research.

They found that indentation level had a statistically significant effect on comprehension, and optimal indentation fell somewhere between 2 and 4 spaces. As the spacing increased beyond that (6 spaces or more), comprehension decreased.

It’s worth noting that all testing was done: (1) in the 1980’s (2) on 80-column-limit systems, and (3) with choices limited to 0, 2, 4, and 6 spaces. “The level of indentation we tested (0-6 spaces) gave strong results favoring 2 or 4 spaces.” The paper recommends that more indentation levels (0-8 spaces, or nine total levels) be studied in further depth. I’m sure someone got around to it before Starbucks and the MacBook Pro were invented.

In contrast, there’s the Jay Bonci codex (Perlmonks, 2002, “The One True Style of indentation“), a sociological introspection of indentation. Here’s a subset of the Bonci codification that maps spacing choices to internal coding intent.

  • One space – Screw readability. I’m pissed they even make me separate my operators. Perl should be more like Latin.
  • Two spaces – I have my head on straight AND I respect screen real estate.
  • Three spaces – I have a little flair, or a nervous twitch. Or the second disguised as the first. Or you listen to waltz while you code.
  • Four spaces – I read a few standards docs and now I think I’m all spiffy. Vannila (sic) Ice, I know you’re in there.
  • Six spaces – I have agression (sic) issues, and my outlet is machine gunning the space bar
  • Eight spaces – You end every line with a meniachal (sic) “DIE! HAHAHAHAH! DIE! YOUR FRIENDS CANNOT SAVE YOU NOW.”
  • Tabs – I’m a lazy person. I know all of the vi commands by heart. Or you drank the 80’s soda.

In the real world, indentation seems to have settled on two, four, and sadly three space standards. So what’s your indentation style? And why?

1  My personal use of 3-space indentations have almost entirely been predicated on accidental deletion of a member of a 4-space unit, but they have happened.

Like my posts? Consider buying a book or two. Thanks!