Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateless static methods vs. C functions in Objective-C

In terms of good Objective-C coding practices, if I create a function that has no state, is it better to write it as a static method of some class or as a C function?

For example, I have a special filepath retrieval method that checks the Caches directory before proceeding to the main NSBundle. I currently have it as a static method under an otherwise empty Utils class. Should this be a C function instead?

The reason I've chosen to use a static method (for now) is that a) it's consistent with Objective-C syntax, and b) the class helps to categorize the method. However, I feel like I'm cheating a little, since I could easily fill up my Util class with these stateless static methods and end up with an ugly "shell class", whose sole purpose would be to hold them.

What convention do you use? Is one "better" than the other, by some objective metric? Thank you!

like image 973
Archagon Avatar asked Oct 10 '22 10:10

Archagon


1 Answers

If you can think of an existing class of which this might make a good method, you can inject your method into it by making an Objective-C category. This keeps your two reasons for using a static method while not polluting the class space with an extra class.

For example:

@interface NSString (MyStringCategories) 
- (NSString*) myCoolMethod;
@end

// [StringCategories.m]
#import "StringCategories.h"

@implementation NSString (MyStringCategories)
- (NSString*) myCoolMethod {
    // do cool stuff here
    return whateverYouLike;
}
@end

Now you can send myCoolMethod to any string. Cool!

In your particular case, it sounds like a method on NSBundle might be an appropriate architecture. And don't forget, it can be a class method, so you don't need to instantiate anything in order to call your method.

like image 96
matt Avatar answered Oct 13 '22 09:10

matt