Static utility classes

Thoughts By 3 years ago

A lot of iOS programmers seem to be using utility classes with a whole bunch of static helper methods. To be honest long ago I did this myself. I believe that this “static utility class” pattern came from other languages, which programmers try and make Objective-C adhere to.

Usually people put things in there when they can’t figure out where else to put them, such as shared date formatters and a bunch of other miscellaneous things.

There’s a whole lot of problems with doing this.

For one, most of your classes will start referencing this utility class, making everything dependant on it.

These utility classes also start getting huge very fast. If you work in a development team, it can become a nightmare having a few developers working on this one class constantly.

Objective-C has a solution for most of these cases anyway!

Most of the time the methods can be moved into a class category, which lets you extend existing classes with new functionality.¬†When your utility method takes a single parameter, that’s usually a good sign that you can instead categorize that parameter’s class and add the functionality there instead.

Take this example

@interface Utility : NSObject

+ (NSString*) MD5ForString:(NSString*) string;

@end
NSString* result = [Utility MD5ForString:@"hello"];

Can instead become

@interface NSString (Hashing)

- (NSString*) MD5;

@end
NSString* result = [@"hello" MD5];

Much nicer, and logical!

If the method is something that reads and saves data, you are usually better off making a standalone class for this, isolating its¬†behaviour. This also makes it easier to write unit tests, testing a single piece of functionality, compared to what’s usually complicated inside a utility class.

If you’re not sure where to fit something other than a utility class, think about which classes the method is interacting with. Usually that’s a good place to start when planning where things need to go.