Saturday, January 5, 2008

Superstrings and symmetry


I like the way I can add local 'special powers' to framework classes such as NSString to extend them to do specific useful things in my app, in keeping with their other more general capabilities.

For example, NSString has methods to create strings from concatenation, or more complex conjoining of components through formating. These are general, naturally. My app required some specific formatting of some strings to make UIDs with variously parseable fields. The methods for this can take specific types for the components, and can perform preflight checks on the validity of these parameters before combining them into the required string image. These methods are specific TO my app, but pretty general WITHIN my app.

So, where should these methods be defined?
- They are essentially pure functions, so should be class methods
- They could be placed on some 'top level' application class as an indicator that they are global to the app
- They could be placed in some kind of 'utility' class, perhaps implying a set of such classes e.g. StringUtils, FileUtils etc.

However, the basic string construction methods are on NSString itself, so wouldn't it be nice to add some methods to this class that are only visible in my app (...Ruby, anyone?). Of course, this is exactly what Objective-C categories allow you to do.

Benefits of doing it the Category way:
1. The formatting methods can be styled exactly like the similar, more general methods on NSString - nice symmetry, and in many ways this has the benefit of being where we expect to find them (though of course you have to include the category to get these additions).
2. We save having to create a slightly naff 'utility class' just to be a home to a few ragbag methods whose only grounding concept is the string.
3. (Compared to something like Ruby)... We get all the proper type checking from the category when calling the class or instance on which the category is defined.

Having said all that, I have no idea about any canon, tradition/religion in the Objective-C or Cocoa community about when and how to use Categories - ergo, whether this is considered de rigueur. However, it seems elegant to me and I'm quite content to make up my own mind on such matters :-)

No comments: