The Shape of Everything
A website mostly about Mac stuff, written by August "Gus" Mueller
» Acorn
» Retrobatch
» Mastodon
» Micro.blog
» Instagram
» Github
» Maybe Pizza?
» Archives
» Feed
» Micro feed
May 16, 2016

Brent Simmons has had some good posts lately on the (lack of) dynamic nature of Swift: The Tension of Swift, A Hypothetical Responder Chain Written in Swift, The Case for Dynamic-Swift Optimism. Manton Reece also has a good take, and Daniel Jalkut is optimistic as always.

Being able to write dynamic, responder chain-like code in Swift or Objective-C (or whatever) is extremely important to me. And if I had to give one reason why it would be this: Dynamic code is less code, and less code means fewer bugs and maintenance.

Here's a simple example. Acorn's canvas class has a neat bit of code where it overrides methodSignatureForSelector:, respondsToSelector:, and forwardInvocation: so that it can either act on a given message or pass that along to the currently selected layer(s). It's 44 lines of code including comments, which I wrote once years ago.

With that in place, I can add a new menu item named "Add Layer Mask" with an action of addLayerMask: and a target of nil. Then in the layer class (or subclass if it's only specific to a bitmap or shape layer) I add a single method named addLayerMask:, and I'm pretty much done after writing the code to do the real work.

When the menu is shown via pull down (or contextual menu, etc.) the responder chain is queried, the frontmost canvas asks the currently selected layers if it responds to this method, and then things go on smoothly as you'd expect from there. Menu items are dynamically enabled or disabled, and then actions are called to perform the method when the menu is selected.

What I didn't add was a giant switch statement like we did in the bad old days of classic Mac OS programming. What I didn't add was glue code in various locations setting up targets and actions at runtime that would have to be massaged and updated whenever I changed something. I'm not checking a list of selectors and casting classes around to make the right calls.

Would a switch statement be faster? Probably. I bet you could shave off nanoseconds. But it's simply not worth it in my opinion.

Other people would disagree of course. But I try to pick my battles wisely.

Would I write dynamic code to do the actual processing of images? Of course not, only an insane person would. Would I use dynamic code for any performance critical path in my application? Again, only crazy people.

Dynamic code lets me cut down on clutter, glue code, and unnecessary boiler plate. It lets me focus on what makes Acorn great and lets me worry about what parts need to be fast and safe. I think making Swift more dynamic, where appropriate, would be a huge boon to app developers everywhere.