Why I don't prefix category methods

· 2 minute read

This weekend I came across a series of tweets from Nick Lockwood explaining why he doesn’t prefix his class category method names, and found fully myself vehemently agreeing with everything he said.

This is dead-on. Unless you’re specifically trying to override existing behavior1, class categories are nothing but syntactic sugar. There’s nothing to be gained functionally by using a category as opposed to simply a function, or class/instance methods on a custom object that you create. It’s simply aesthetic preference.

If you think creating unprefixed class category methods is unsafe because Apple could potentially add a method that collides with yours in the future, please realize that this could also happen to any method on any custom class in your application. Apple adds new methods to NSObject and other commonly subclassed base classes all the time. Categories are hardly the only place where such a problem could arise.

If you’re releasing a class category as part of an open-source library, it may make sense to prefix its methods. However, even then I have my doubts. If the library only uses these category methods internally, then yes, prefix them to prevent against collisions with any other open-source code that the developer using your code may have also imported. But again, in this case I’m not sure using a category really buys you very much. If the category itself is expected to be used directly by third-party developers, the original point remains: is using a prefixed category method any cleaner looking than a utility class? I tend to think not.

UPDATE: Both Brian Bonczek and Jared Sinclair have pointed out a benefit of prefixing category methods that I somehow overlooked: to prevent collisions with third-party dependencies that you include. But again I question the general usefulness of third-party categories as opposed to utility classes.


Originally published on cocoa.tumblr.com

  1. In which case you wouldn’t be using a prefix anyway.