Getting Over Objective-C Verbosity
Everyone knows Objective-C is very verbose. Some people like it because it can be easier to understand when you know what the five parameters in a particular method actually mean. Many people dislike it though, as it takes a long time to type things out.
There are a couple of solutions to getting around its verbosity:
- Suck it up and get on with it
- Macros for most used functions
- Code snippets
For a long time I kind of just went along with #1 - I never found it a deal breaker since I type at a pretty quick rate (typing tests put me at 130+ WPM) but obviously there’s no point in giving myself RSI when I don’t need to!
So, macros! A feature of an age long past. Just kidding. They have their place, but I just don’t think it’s here. I’ve seen developers use macros for common functions such as
[NSString stringWithFormat:] or
[UIColor colorWithRed:green:blue:alpha:], replacing them with something like
COLOR(r, g, b, a).
Fair enough, you cut down a few characters. If you’re doing it a lot, you’ve saved yourself some time there!
My issues with the macro method are:
- Hard to debug when using macros - self-explanatory
- If I were to join a project down the line and see files filled with this sort of thing I’d bang my head on the desk. How is the developer supposed to know what each macro does? FORMAT and COLOR are awful names, and when you start making them longer, the gain you had before begins to disappear - you may as well use Xcode’s autocompletion.
Which brings me to my solution: code snippets. They’ve been around for a long time in Xcode, but don’t get nearly as much attention as they should do.
Here’s a quick guide to creating a code-snippet:
- Write a bit of code, highlight, drag-and-drop to the code snippet window, and a new snippet is added.
- Take out any absolute values you may have entered, and replace with
<# parameter #>with parameter being what you want to be shown to the developer that uses the snippet.
- Set the “completion scope” of the snippet - usually this will just be function or method, but it depends on your snippet.
- Set the “completion shortcut”. This is what you, the developer, will begin typing to get Xcode’s auto-completion to work for your snippet.
So as an example, I created a snippet for
stringWithFormat that has
swf as the completion shortcut. The snippet is only on my Xcode environment - no other developer knows any different, all they see is the full
stringWithFormat method being called.
I’m not discounting macros entirely - I just think for this particular case, code snippets are the way to go. Of course, this is entirely subjective, and some developers would prefer to use macros. If you are one of these developers, and you’re on a team, please consult other developers on this.