views:

203

answers:

2

When reading Best way to define private methods for a class in Objective-C I end up with a programming style doubt. Which is the better solution (in terms of style) to this problem? To use a category and declare it in the @interface directive in the .m file or go with the static function that receives an object.

Thanks

+6  A: 

Categories are the way to go.

The Google Objective-C Style Guide says,

Use a private category to prevent cluttering the public header.

If you are using Objective-C 2.0, you should instead declare your private category using a class extension, for example: @interface GMFoo () { ... } which will guarantee that the declared methods are implemented in the @implementation section by issuing a compiler warning if they are not.

"A class extension is declared just like a category, but without a name"
--Class Extensions Explained

Vincent Gable
+1 - Method are the way to go. The private method of today, is likely to be cleaned up and a public method in the future. Be prepared.
PeyloW
+1  A: 

If you do not have an immediate answer as to which to use, prefer functions.

I use functions most of the time (> 90%).

Methods are useful for polymorphism and the interface.

There are other considerations for each:

Functions will generally be smaller, faster, and the compiler has the ability to inline them. If there is no reason to cause a problem by using a method and you do not need to have any exclusive in-class use, then go with the function.

Methods (or categories, if you prefer) are handy if you don't want accessor overhead or want some other feature which is available in the instance method, such as @synchronized. In my programs, these features are far less likely, and there is usually no need to use methods.

Methods export additional symbols, and generally incur a higher (but small) overhead, as a result, they typically make the binary slightly larger and the executable slightly slower (not usually noticed, unless you use them often).

There is also a risk in using/creating private methods, in that receivers/subclasses may implement/declare the method. It's often an unnecessary risk. I prefer the compiler/linker to sort this out for me, rather than find out that it is hitting an odd case at runtime 2 weeks after shipping (and difficult to locate the problem). Methods may also be useful if you intend on making the interface public sometime soon.

Justin